You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio中使用Retrofit时API Key的放置位置与语法问题

How to Add NewsAPI Key to Your Retrofit Request Interface

Hey there! Let's sort out how to properly include your NewsAPI key in your Retrofit interface. NewsAPI requires all requests to be authenticated, and there are two straightforward ways to do this with Retrofit—using a query parameter or a request header. I'll walk you through both options, plus a bonus tip to avoid repeating the key in every call.

Option 1: Pass API Key as a Query Parameter

NewsAPI accepts the API key via an apiKey query parameter. Here's how to modify your existing interface to include this:

public interface RequestInterface {
    // Replace "top-headlines" with your target NewsAPI endpoint (e.g., "everything", "sources")
    // Add other required query params like country/category as needed
    @GET("top-headlines")
    Call<JSONResponse> getJSON(@Query("apiKey") String apiKey, @Query("country") String country);
}

When you call this method in your MainActivity, just pass your actual API key along with other parameters:

// Initialize your Retrofit client first (make sure baseUrl is set to "https://newsapi.org/v2/")
RequestInterface requestInterface = retrofit.create(RequestInterface.class);
Call<JSONResponse> call = requestInterface.getJSON("YOUR_ACTUAL_NEWSAPI_KEY", "us");

// Proceed with enqueueing the call as you would normally
call.enqueue(new Callback<JSONResponse>() {
    @Override
    public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
        // Handle successful response
    }

    @Override
    public void onFailure(Call<JSONResponse> call, Throwable t) {
        // Handle error
    }
});

Option 2: Pass API Key in a Request Header

Alternatively, you can send the API key in the X-Api-Key request header. This keeps your query parameters cleaner:

public interface RequestInterface {
    @GET("top-headlines")
    Call<JSONResponse> getJSON(@Header("X-Api-Key") String apiKey, @Query("country") String country);
}

The call in MainActivity stays almost identical—you just pass the key to the apiKey parameter as before.

Bonus: Add API Key Globally with an Interceptor

If you don't want to pass the API key every time you make a request, you can use an OkHttp Interceptor to automatically add it to all outgoing requests. This is great for keeping your code DRY:

First, set up your OkHttpClient with the interceptor:

OkHttpClient okHttpClient = new OkHttpClient.Builder()
    .addInterceptor(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            // Add the API key header to the original request
            Request modifiedRequest = originalRequest.newBuilder()
                .header("X-Api-Key", "YOUR_ACTUAL_NEWSAPI_KEY")
                .build();
            return chain.proceed(modifiedRequest);
        }
    })
    .build();

Then attach this client to your Retrofit instance:

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://newsapi.org/v2/")
    .client(okHttpClient)
    .addConverterFactory(GsonConverterFactory.create())
    .build();

Now your interface can omit the API key parameter entirely:

public interface RequestInterface {
    @GET("top-headlines")
    Call<JSONResponse> getJSON(@Query("country") String country);
}

Quick Note

Don't forget to replace the tutorial's test endpoint (android/jsonandroid) with a valid NewsAPI endpoint (like top-headlines or everything) and set your Retrofit base URL to https://newsapi.org/v2/—that's the base URL for all NewsAPI requests.

内容的提问来源于stack exchange,提问作者Abhishek Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:23:40