2

I am creating a News app using api key from newsapi.org This is my code for Interface which i have created using tutorial found on https://www.learn2crack.com/2016/02/recyclerview-json-parsing.html.I am confused what is the syntax and where to put api key in this interface.

public interface RequestInterface {

@GET("android/jsonandroid")
Call<JSONResponse> getJSON();}

and this is my code for MainActivity.java

public class MainActivity extends AppCompatActivity {
    private RecyclerView recyclerView;
    private ArrayList<Article> data;
    private DataAdapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();
    }
    private void initViews(){
        recyclerView = (RecyclerView)findViewById(R.id.card_recycler_view);
        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(layoutManager);
        loadJSON();
    }
    private void loadJSON(){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("BASE_URL")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        RequestInterface request = retrofit.create(RequestInterface.class);
        Call<JSONResponse> call = request.getJSON();
       call.enqueue(new Callback<JSONResponse>() {
           @Override
           public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
               JSONResponse jsonResponse = response.body();
               data = new ArrayList<>(Arrays.asList(jsonResponse.getAndroid()));
               adapter = new DataAdapter(data);
               recyclerView.setAdapter(adapter);
           }

           @Override
           public void onFailure(Call<JSONResponse> call, Throwable t) {
               Log.d("Error",t.getMessage());
           }
       });
    }
}
ADM
  • 18,477
  • 11
  • 47
  • 78

2 Answers2

2

Use @Headers for one request:

@Headers("api-key: " + "PUT_YOUR_API_KEY")
@GET("android/jsonandroid")
Call<JSONResponse> getJSON();
}

and use addInterceptor in OkHttpClient.Builder for all requests:

OkHttpClient.Builder builder = new OkHttpClient.Builder();

builder.addInterceptor(new Interceptor() {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request().newBuilder().addHeader("api-key", "PUT_YOUR_API_KEY").build();
            return chain.proceed(request);
    }
});
Tim Diekmann
  • 6,764
  • 10
  • 34
  • 58
Saeed Fekri
  • 797
  • 4
  • 10
  • Doens't work for me: https://stackoverflow.com/questions/68211912/android-retrofit-okhttpclient-interceptor-add-header-gets-error-http-403-forbid – Sam Chen Jul 01 '21 at 14:20
0

For newsapi.org, suppose your source is mashable try this

public interface RequestInterface {
@GET("v1/articles?source=mashable&sortBy=top&apiKey=your_apikey_here")
Call<JSONResponse> getJSON();
}

and this should be baseurl

Retrofit retrofit = new Retrofit.Builder()

            .baseUrl("https://newsapi.org/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();
Navneet Krishna
  • 4,931
  • 5
  • 23
  • 42
  • 2
    Queries should be set as a parameter on the interface: @GET("v1/articles") Call getJson( @Query("source") String source, @Query("sortBy") String sortBy, @Query("apiKey") String apiKey); – Alvin Rusli Apr 18 '18 at 04:49
  • yes, that is a better solution if the query params are meant to be dynamically changed(above solution should also work) – Navneet Krishna Apr 18 '18 at 04:55