Created
October 12, 2017 02:17
-
-
Save twaddington/e66e495e14950b4437216ab5c704835b to your computer and use it in GitHub Desktop.
Injects a User-Agent header into outgoing OkHttp requests.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.enlighthq.mobile.http; | |
import android.os.Build; | |
import java.io.IOException; | |
import java.util.Locale; | |
import okhttp3.Interceptor; | |
import okhttp3.Request; | |
import okhttp3.Response; | |
/** | |
* Adds a custom {@code User-Agent} header to OkHttp requests. | |
*/ | |
public class UserAgentInterceptor implements Interceptor { | |
public final String userAgent; | |
public UserAgentInterceptor(String userAgent) { | |
this.userAgent = userAgent; | |
} | |
public UserAgentInterceptor(String appName, String appVersion) { | |
this(String.format(Locale.US, | |
"%s/%s (Android %s; %s; %s %s; %s)", | |
appName, | |
appVersion, | |
Build.VERSION.RELEASE, | |
Build.MODEL, | |
Build.BRAND, | |
Build.DEVICE, | |
Locale.getDefault().getLanguage())); | |
} | |
@Override | |
public Response intercept(Chain chain) throws IOException { | |
Request userAgentRequest = chain.request() | |
.newBuilder() | |
.header("User-Agent", userAgent) | |
.build(); | |
return chain.proceed(userAgentRequest); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment