3

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
  • 20,406
  • 11
  • 52
  • 83
Abhishek Kumar
  • 53
  • 1
  • 1
  • 7

3 Answers3

5

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
  • 7,755
  • 11
  • 41
  • 69
Saeed Fekri
  • 1,067
  • 9
  • 12
  • 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
  • 5,009
  • 5
  • 25
  • 44
  • 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
0

To answer the "where" question, from my understanding, it depends on the API you're calling. You may put it in header or as a query for instance.

The good way to do it if you need to use the key for every calls is to add an Interceptor.

private fun apiKeyAsQuery(chain: Interceptor.Chain) = chain.proceed(
        chain.request()
            .newBuilder()
            .url(chain.request().url.newBuilder().addQueryParameter("api-key", ApiKey).build())
            .build()
    )

private fun apiKeyAsHeader(it: Interceptor.Chain) = it.proceed(
    it.request()
        .newBuilder()
        .addHeader("api-key", ApiKey)
        .build()
)

...
.client(
    OkHttpClient.Builder()
        .addInterceptor { apiKeyAsQuery(it) }
        // Or
        .addInterceptor { apiKeyAsHeader(it) }
        .build()
)
...

Nicolas Duponchel
  • 1,219
  • 10
  • 17