Getting Header from Response (Retrofit / OkHttp Client)

54,701

Solution 1

With Retrofit 1.9.0, if you use the Callback asynchronous version of the interface,

@GET("/user")
void getUser(Callback<User> callback)

Then your callback will receive a Response object

    Callback<User> user = new Callback<User>() {
        @Override
        public void success(User user, Response response) {

        }

        @Override
        public void failure(RetrofitError error) {

        }
    }

Which has a method called getHeaders()

    Callback<User> user = new Callback<User>() {
        @Override
        public void success(User user, Response response) {
            List<Header> headerList = response.getHeaders();
            for(Header header : headerList) {
                Log.d(TAG, header.getName() + " " + header.getValue());
            }
        }

For Retrofit 2.0's interface, you can do this with Call<T>.

For Retrofit 2.0's Rx support, you can do this with Observable<Result<T>>

Solution 2

In Retrofit 2.0.0, you can get header like this:

public interface Api {
    @GET("user")
    Call<User> getUser();
}

Call<User> call = api.getUser();
call.enqueue(new Callback<User>() {
    @Override
    public void onResponse(Call<User> call, Response<User> response) {
        // get headers
        Headers headers = response.headers();
        // get header value
        String cookie = response.headers().get("Set-Cookie");
        // TODO
    }

    @Override
    public void onFailure(Call<User> call, Throwable t) {
        // TODO
    }
});

Solution 3

Much like you I wanted the headers along side of the payload. I needed access to the Etag. It takes some retro-foo, but you can do it. here's what I did. It's a dirty sample so dont take this as a best practices sample.

public static RestAdapter.Builder getRestBuilder(Context context) {
    GsonBuilder gsonBuilder = GsonBuilderUtils.getBuilder();
    Gson gson = gsonBuilder.create();
    // **
    // 1. create our own custom deserializer here
    // **
    final MyGsonConverter gsonConverter = new MyGsonConverter(gson);
    OkHttpClient httpClient = MyPersonalOkHttpFactory.getInstance().getAuthHttpClient(context);
    httpClient.networkInterceptors().add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            Response response = chain.proceed(originalRequest);
            // **
            // 2. add the headers from the Interceptor to our deserializer instance
            // **
            gsonConverter.headers = response.headers();
            return response;
        }
    });
    RestAdapter.Builder builder = new RestAdapter.Builder()
            .setClient(new OkClient(httpClient))
            .setEndpoint(Common.getApiOriginUrl())
            .setConverter(gsonConverter);
    return builder;
}

private static class MyGsonConverter extends GsonConverter {

    private Headers headers;

    public MyGsonConverter(Gson gson) {
        super(gson);
    }

    @Override
    public Object fromBody(TypedInput body, Type type) throws ConversionException {
        Object obj =  super.fromBody(body, type);
        // **
        // 3. at this point, gson is called and you have access to headers
        // do whatever you want here. I just set it on the return object.
        // ** 
        if (obj instanceof HeadersArrayList) {
            ((HeadersArrayList)obj).setHeaders(headers);
        }
        return obj;
    }
}

public class HeadersArrayList<K> extends ArrayList<K>{

    private Headers headers;

    public Headers getHeaders() {
        return headers;
    }

    public void setHeaders(Headers headers) {
        this.headers = headers;
    }
}

// the retrofit api for reference
@GET("/api/of/my/backend/{stuff}")
HeadersArrayList<String> getSomething(@Path("stuff") String stuff);
Share:
54,701
dknaack
Author by

dknaack

Updated on August 12, 2022

Comments

  • dknaack
    dknaack almost 2 years

    I am using Retrofit with the OkHttp Client and Jackson for Json Serialization and want to get the header of the response.

    I know that i can extend the OkClient and intercept it. But this comes before the deserialization process starts.

    What i basically needs is to get the header alongside with the deserialized Json Object.

  • Sakiboy
    Sakiboy almost 8 years
    Is there a way to get it synchronously?
  • EpicPandaForce
    EpicPandaForce almost 8 years
    In Retrofit 1.9.0 no, in Retrofit 2.0+ yes (using Call<T>.execute())
  • Lester
    Lester almost 8 years
    How i can do that with observables?
  • murt
    murt almost 8 years
    @EpicPandaForce have you already overridden it and want to share?
  • EpicPandaForce
    EpicPandaForce over 7 years
    @murt the newest code in the Github repository seems to be able to allow you to specify Observable<Result<T>> which gives you response as a parameter, and response has the headers.
  • EpicPandaForce
    EpicPandaForce over 7 years
    @murt actually, now that i read even further, you should be able to obtain Observable<Result<T>> even with your current version. Sorry about the initial misinformation :(
  • EpicPandaForce
    EpicPandaForce over 7 years
    @Lester apparently I was wrong previously, and you should be able to obtain an Observable<Result<T>> which has the headers too.
  • murt
    murt over 7 years
    @EpicPandaForce So I wanted to walk around using Response<mObject> in odred to read header. What I did. I use singleton which collects header data - like token and I've applied reference of it to Interceptor. In incterceptor I may read response header simultanieously using Observable<mObject> as returned response. I handle error by Overriding onErrorResumeNext(Throwable) in RxJavaAdapterFactory. Every thing is automatic now and works as I wanted - so concerns are separated.
  • Prabs
    Prabs almost 7 years
    how do I loop through all headers? I've 4-5 headers with "set-cookie" as a key.
  • Prabs
    Prabs almost 7 years
    List<String> cookieList = headers.toMultimap().get("set-cookie"); using foreach iterate through the list
  • Edi
    Edi over 6 years
    Or like this: headers.values("Set-Cookie").
  • Kidus Tekeste
    Kidus Tekeste about 4 years
    if you're looking for RxJava + Retrofit full response from API with the header and body information then you can use this -> Observable<Response<ResponseBody>>