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;

    public Response intercept(Chain chain) throws IOException {
        Request originRequest = chain.request();
        Request requestWithUserAgent = originRequest.newBuilder()
                                                    .header("User-Agent", userAgent)
        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("");
Retrofit retrofit = builder.client(okHttp).build();


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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