Retrofit2 + OkHttp3设置Http请求头(Headers)方法汇总
Posted 一起学习_Program
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Retrofit2 + OkHttp3设置Http请求头(Headers)方法汇总相关的知识,希望对你有一定的参考价值。
在构建网络层时会遇到一个问题就是要手动配置Http请求的Headers,写入缓存Cookie,自定义的User-Agent等参数,但是对于有几十个接口的网络层,我才不想用注解配置Headers,目前网上很多文章的方法真对这两个版本都不是很适用,有的给出的方法已经被删除,有的方法会报出异常
:(
方法一:
在翻阅官方API文档整理后的方法如下:
1. import okhttp3.Interceptor;
2. import okhttp3.OkHttpClient;
3. import okhttp3.Request;
4. import okhttp3.Response;
5. import retrofit2.Retrofit;
6.
7. public class RetrofitAPIManager {
8.
9. public static final String SERVER_URL = "url";
10.
11. public static ClientAPI provideClientApi() {
12. Retrofit retrofit = new Retrofit.Builder()
13. .baseUrl(SERVER_URL)
14. .client(genericClient())
15. .build();
16. return retrofit.create(ClientAPI.class);
17. }
18.
19.
20. public static OkHttpClient genericClient() {
21. OkHttpClient httpClient = new OkHttpClient.Builder()
22. .addInterceptor(new Interceptor() {
23. @Override
24. public Response intercept(Chain chain) throws IOException {
25. Request request = chain.request()
26. .newBuilder()
27. .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
28. .addHeader("Accept-Encoding", "gzip, deflate")
29. .addHeader("Connection", "keep-alive")
30. .addHeader("Accept", "*/*")
31. .addHeader("Cookie", "add cookies here")
32. .build();
33. return chain.proceed(request);
34. }
35.
36. })
37. .build();
38.
39. return httpClient;
40. }
41. }
使用Interceptor来拦截并重新设置请求头,测试可用
- List<Interceptor> interceptors()方法,返回的是一个不可编辑的列表,如果对其进行编辑会报出UnSupportedOperationException
- Interceptor的典型使用场景,就是对request和response的Headers进行编辑
方法二.、
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.cookieJar(new CookieJar() {
private final HashMap<HttpUrl, List<Cookie>> cookieStore = new HashMap<>();
@Override
public void saveFromResponse(HttpUrl httpUrl, List<Cookie> list) {
cookieStore.put(httpUrl, list);
}
@Override
public List<Cookie> loadForRequest(HttpUrl httpUrl) {
List<Cookie> cookies = cookieStore.get(httpUrl);
return cookies != null ? cookies : new ArrayList<Cookie>();
}
}).build();
方法三、
Request request = new Request.Builder()
.url(PATH)
.post(body)
//取出本地保存的sessionId
.addHeader("Cookie", "sessionId")
.build();
Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()){
Headers headers = response.headers();
List<String> cookies = headers.values("Set-Cookie");
Log.d(TAG, "onResponse: "+cookies.size());
for (String str:cookies){
if (str.startsWith("phpSESSID")){
//将sessionId保存到本地
Log.d(TAG, "onResponse: "+str.split(";")[0]);
}
}
}
}
});
以上是关于Retrofit2 + OkHttp3设置Http请求头(Headers)方法汇总的主要内容,如果未能解决你的问题,请参考以下文章
http2 似乎不适用于 OkHttp3 和 retrofit2
Android网络实战篇——OkHttp3(Retrofit2)五种缓存模式的实现
Android Okhttp3+Retrofit2网络加载效率优化
Retrofit2.0 ,OkHttp3完美同步持久Cookie实现免登录