Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Square's Retrofit Android: Hash With Contents of Request

Tags:

android

hash

I want to create a hash with some parts of my request using Square's Retrofit library. The RequestInterceptor does not help me because it does not provide information about the request, it just makes possible to add information to it. I need to access the HTTP verb, all the headers and the REST path to create the hash. The hash would be added to the Authorization header. Any ideas?

like image 317
Marcelo Benites Avatar asked Oct 21 '22 13:10

Marcelo Benites


1 Answers

In order to accomplish this with Retrofit 1.9.0 the only way is to use OkHttp interceptors (https://github.com/square/okhttp/wiki/Interceptors). The following code uses OkHttp 2.2.0:


    public class YourInterceptor implements Interceptor {

    @Override public Response intercept(Chain chain) throws IOException {

        Request request = chain.request();

        if (request != null) {
            RequestBody body = request.body();
            URL requestURL = request.url();
            String method = request.method();
            Headers headers = request.headers();

            Request.Builder signedRequestBuilder = request.newBuilder();
            signedRequestBuilder.addHeader("Authorization", "Your Signature");
            request = signedRequestBuilder.build();
        }
        return chain.proceed(request);
    }
}

. . .

OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.interceptors().add(new YourInterceptor());
RestAdapter restAdapter = new RestAdapter.Builder()
    .setClient(new OkClient(okHttpClient))
    .build();

like image 192
Marcelo Benites Avatar answered Oct 23 '22 11:10

Marcelo Benites