我是android的新手。任何人都告诉我如何使用retrofit为api_key添加标题。我无法理解我是如何做到的。
我从net.where找到这个代码我必须将此代码放在android文件夹结构中。我对此感到困惑。我必须添加api_key。
// Define the interceptor, add authentication headers
Interceptor interceptor = new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request newRequest = chain.request().newBuilder().addHeader("User-Agent", "Retrofit-Sample-App").build();
return chain.proceed(newRequest);
}
};
// Add the interceptor to OkHttpClient
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.interceptors().add(interceptor);
OkHttpClient client = builder.build();
// Set the custom client when building adapter
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
答案 0 :(得分:1)
您可以将api_key存储在strings.xml文件中,如下所示:
<string name="your_api_key_id" translatable="false">YOUR_API_KEY</string>
然后,在你的OkHttpClient定义类中,编写一个方法来构建你的OkHttpClient:
private final static String API_KEY_IDENTIFIER = "key_identifier";
private OkHttpClient getHttpClient(){
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
HttpUrl originalUrl = original.url();
HttpUrl url = originalUrl.newBuilder()
.addQueryParameter(API_KEY_IDENTIFIER, mContext.getString(R.string.your_api_key_id))
.build();
Request.Builder requestBuilder = original.newBuilder().url(url);
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
return httpClient.build();
}
您应该使用Singleton模式实现客户端构建器类,以便将客户端构建集中在代码中的一个位置