Add User Agent in Retrofit 2

I’m using retrofit for my android http library and I just know that by default there’s no “User-Agent” inside request header.
Because I have to check coming request in my backend, so I identify by “User-Agent” and I have to attach user agent to my entire request on my android project to deal with it.

Here is code snippet to add “User-Agent” to all retrofit request (I used retrofit 2)

public class UserAgentInterceptor implements Interceptor {

    private final String userAgent;

    public UserAgentInterceptor(String userAgent) {
        this.userAgent = userAgent;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request originRequest = chain.request();
        Request requestWithUserAgent = originRequest.newBuilder()
                                                    .header("User-Agent", userAgent)
                                                    .build();
        return chain.proceed(requestWithUserAgent);
    }
}

And the last, what you need to do is register the interceptor above to our OKHttp inside retrofit.

String UA = System.getProperty("http.agent");  // Get android user agent.

OkHttpClient okHttp = new OkHttpClient()
okHttp.interceptors().add(new UserAgentInterceptor(UA));

Retrofit.Builder builder = new Retrofit.Builder().baseUrl("http://your-base-url.com/");
Retrofit retrofit = builder.client(okHttp).build();

Reference: http://stackoverflow.com/a/27840834/1936697

One response to “Add User Agent in Retrofit 2”

  1. […] should use an okhttp Interceptor. An example that I’ve found explains how this should be done(Link) but then I am not sure on how to register the […]

    Like

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.