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的典型使用場景,就是對requestresponseHeaders進行編輯

方法二.

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]);
                       }
                   }

               }
            }
        });






免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM