Android 如何为 okhttp 2.x 请求指定默认用户代理
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26509107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to specify a default user agent for okhttp 2.x requests
提问by dimsuz
I am using okhttp 2.0 in my Android app and didn't find a way to set some common User Agent for all outgoing requests.
我在我的 Android 应用程序中使用 okhttp 2.0,但没有找到为所有传出请求设置一些通用用户代理的方法。
I thought I could do something like
我以为我可以做类似的事情
OkHttpClient client = new OkHttpClient();
client.setDefaultUserAgent(...)
...but there's no such method or similar.
Of course I could provide some extension utility method which would wrap a RequestBuilder to attach .header("UserAgent")
and then I would use it for building all my requests, but I thought maybe I missed some existing and simpler way?
...但没有这样的方法或类似的方法。当然,我可以提供一些扩展实用程序方法,它可以包装一个 RequestBuilder 以进行附加.header("UserAgent")
,然后我将使用它来构建我的所有请求,但我想也许我错过了一些现有的更简单的方法?
回答by josketres
You can use an interceptor to add the User-Agent header to all your requests.
您可以使用拦截器将 User-Agent 标头添加到您的所有请求中。
For more information about okHttp interceptors see http://square.github.io/okhttp/interceptors/
有关 okHttp 拦截器的更多信息,请参阅http://square.github.io/okhttp/interceptors/
Example implementation of this interceptor:
此拦截器的示例实现:
/* This interceptor adds a custom User-Agent. */
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 originalRequest = chain.request();
Request requestWithUserAgent = originalRequest.newBuilder()
.header("User-Agent", userAgent)
.build();
return chain.proceed(requestWithUserAgent);
}
}
Test for the UserAgentInterceptor:
测试 UserAgentInterceptor:
public void testUserAgentIsSetInRequestHeader() throws Exception {
MockWebServer server = new MockWebServer();
server.enqueue(new MockResponse().setBody("OK"));
server.play();
String url = server.getUrl("/").toString();
OkHttpClient client = new OkHttpClient();
client.networkInterceptors().add(new UserAgentInterceptor("foo/bar"));
Request testRequest = new Request.Builder().url(url).build()
String result = client.newCall(testRequest).execute().body().string();
assertEquals("OK", result);
RecordedRequest request = server.takeRequest();
assertEquals("foo/bar", request.getHeader("User-Agent"));
}
回答by Jake Wharton
OkHttp v2.1 which is set to be released in the next few weeks will automatically seta User-Agent
header if one is not already set.
这将在未来几周内发布OkHttp V2.1将自动设置一个User-Agent
,如果一个尚未设置标题。
As of now there isn't a good way to add this header to every request in a centralized way. The only workaround is to include the header manually for every Request
that is created.
到目前为止,还没有一种好的方法可以以集中的方式将此标头添加到每个请求中。唯一的解决方法是手动包含每个Request
创建的标头。
回答by willcwf
In case anyone is looking for this working with OkHttp 3 and in Kotlin:
如果有人正在寻找与 OkHttp 3 和 Kotlin 一起使用的这个:
val client = OkHttpClient.Builder()
.addNetworkInterceptor { chain ->
chain.proceed(
chain.request()
.newBuilder()
.header("User-Agent", "COOL APP 9000")
.build()
)
}
.build()
回答by Saket
Using an intercepter is no longer required in the newer versions of OkHttp. Adding a user agent is as simple as:
在较新版本的 OkHttp 中不再需要使用拦截器。添加用户代理非常简单:
Request request = new Request.Builder()
.url("http://www.publicobject.com/helloworld.txt")
.header("User-Agent", "OkHttp Example")
.build();
Source: OkHttp wiki.
来源:OkHttp 维基。
回答by friederbluemle
Based on @josketres answer, here is a similar Interceptor for OkHttp version 3
基于@josketres 的回答,这里有一个类似的OkHttp 版本 3拦截器
public class UserAgentInterceptor implements Interceptor {
private final String mUserAgent;
public UserAgentInterceptor(String userAgent) {
mUserAgent = userAgent;
}
@Override
public Response intercept(@NonNull Chain chain) throws IOException {
Request request = chain.request()
.newBuilder()
.header("User-Agent", mUserAgent)
.build();
return chain.proceed(request);
}
}
Plus the updated test:
加上更新的测试:
@Test
public void testUserAgentIsSetInRequestHeader() throws IOException, InterruptedException {
final String expectedUserAgent = "foo/bar";
MockWebServer server = new MockWebServer();
server.enqueue(new MockResponse().setBody("OK"));
server.start();
OkHttpClient.Builder okHttpBuilder = new OkHttpClient.Builder();
okHttpBuilder.addInterceptor(new UserAgentInterceptor(expectedUserAgent));
Request request = new Request.Builder().url(server.url("/").url()).build();
ResponseBody result = okHttpBuilder.build().newCall(request).execute().body();
assertNotNull(result);
assertEquals("OK", result.string());
assertEquals(expectedUserAgent, server.takeRequest().getHeader("User-Agent"));
}