How to get the header information of the response when Android uses retrofit

Source: Internet
Author: User

This problem, I encountered in the project in the previous period of use retrofit, finally found the solution there are two ways to get response headers, the first is directly in the definition interface is to let the interface return retrofit response object, You can get to headers in the response object, such as:

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

When manipulating response objects, use Response.headers (); Get headers.

It's not a good idea to modify all of the interfaces, and I've got another way of querying the official documents, which is to build retrofit Apiservice, add interceptor to Okhttpclient, Used to intercept requests and responses to get the request header and response header. This method can be used for Retrofit2 and OKHTTP3.

 Public Staticokhttpclient genericclient () {okhttpclient httpClient=NewOkhttpclient.builder (). Addinterceptor (NewInterceptor () {@Override PublicResponse Intercept (Chain Chain) throws IOException {Response Response=Chain.proceed (Chain.request ()); //Deposit Session                        if(Response.header ("Set-cookie") !=NULL) {sessionmanager.setsession (Response.header ("Set-cookie")); }                        //Refresh API call timeSessionmanager.setlastapicalltime (System.currenttimemillis ()); returnresponse;            }}). Build (); returnhttpClient; }  

One thing to note is that interceptor must be added at Okhttpclient build time, and Okhttpclient's interceptors () method returns a list that is not editable and, if modified, will produce unsupportedoperationexception.

New Retrofit.builder ()                                 ... = Retrofit.create (userservice.  Class); call <User> Call  = userservice.loaduser (); Response<User> Response == Response.raw (); Headers Headers  = Okresponse.headers ();

And then you'll check the Okhttp API.

How to get the header information of the response when Android uses retrofit

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.