标签:
在构建网络层时会遇到一个问题就是要手动配置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来拦截并重新设置请求头,测试可用
方法二.、
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)方法汇总
标签:
原文地址:http://www.cnblogs.com/ut2016-progam/p/5639250.html