Android 使用retrofit時,怎樣擷取響應的頭資訊

來源:互聯網
上載者:User

標籤:raw   ...   tpc   set   cut   cookie   generic   current   tla   

這個問題,我前段時間在項目中使用Retrofit遇到過,最後查到的解決辦法有兩種擷取Response Headers的方法,第一種是直接在定義介面是讓介面返回Retrofit的Response對象,在Response對象中可以擷取到Headers,如:

@GET("/****act=****")Response<SomeClass> getSomeData();

在操作Response對象時,使用response.headers();得到Headers。

這樣做需要修改所有的介面,不是一個很好的辦法,我在查詢官方文檔得到了另外一個方法,就是在構建Retrofit的APIService,在OkHttpClient中加入Interceptor,用以攔截請求和響應擷取要求標頭和回應標頭。此方法可用於Retrofit2和OKHttp3.

public static OkHttpClient genericClient() {          OkHttpClient httpClient = new OkHttpClient.Builder()                  .addInterceptor(new Interceptor() {                      @Override                      public Response intercept(Chain chain) throws IOException {                         Response response = chain.proceed(chain.request());                        //存入Session                        if (response.header("Set-Cookie") != null) {                            SessionManager.setSession(response.header("Set-Cookie"));                        }                        //重新整理API調用時間                        SessionManager.setLastApiCallTime(System.currentTimeMillis());                                                return response;                    }                    })                  .build();            return httpClient;      }  

需要注意的一點是,Interceptor必須在OkHttpClient構建時加入,OKHttpClient的interceptors()方法返回的是一個不可編輯的列表,如果對其進行修改操作,會產生UnSupportedOperationException。

 

 

Retrofit retrofit = new Retrofit.Builder()...                                .build();UserService userService = retrofit.create(UserService.class);Call<User> call  = userService.loadUser();Response<User> response = call.execute();okhttp3.Response okResponse = response.raw();Headers headers  = okResponse.headers();

然後你就查okhttp的api好了

Android 使用retrofit時,怎樣擷取響應的頭資訊

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.