简体   繁体   中英

Retrofit/Robospice: get response headers from successful request?

I am using Retrofit/Robospice to make api calls in an app I've built, with a RetrofitGsonSpiceService. All responses are converted into POJOs using a GSON converter, however there is some information I need to retrieve from the response header. I cannot find any means to get the headers (I can only get the headers if the request is unsuccessful because the raw response is sent in the error object!) how can I intercept the response to grab the headers before it is converted?

It took me a few minutes to figure out exactly what @mato was suggesting in his answer. Here's a concrete example of how to replace the OkClient that comes with Retrofit in order to intercept the response headers.

public class InterceptingOkClient extends OkClient
{
    public InterceptingOkClient()
    {
    }

    public InterceptingOkClient(OkHttpClient client)
    {
        super(client);
    }

    @Override
    public Response execute(Request request) throws IOException
    {
        Response response = super.execute(request);

        for (Header header : response.getHeaders())
        {
            // do something with header
        }

        return response;
    }
}

You then pass an instance of your custom client to the RestAdapter.Builder :

RestAdapter restAdapter = new RestAdapter.Builder()
    .setClient(new InterceptingOkClient())
    ....
    .build();

RoboSpice was designed in a way it doesn't know anything about the HTTP client you end up using in your app. That being said, you should get the response headers from the HTTP client. As Retrofit may use Apache , OkHttp or the default Android HTTP client, you should take a look and see which client you are currently using. Take into account that Retrofit chooses the HTTP client based on certain things (please refer to the Retrofit documentation, or dig into the code, you will find it), unless you manually specify it.

Retrofit defines an interface for clients called Client . If you take a look at the source code, you will see that three classes implement this interface: ApacheClient , OkClient and UrlConnectionClient . Depending on which of them you want to use, extend from one of those, and try to hook into the code that is executed when a response comes back, so that you can get the headers from it.

Once you do that, you have to set your custom Client to Retrofit .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM