android 如何为okhttp 2.x请求指定默认用户代理

sbtkgmzw  于 2023-03-21  发布在  Android
关注(0)|答案(7)|浏览(239)

我在我的Android应用程序中使用okhttp 2.0,没有找到一种方法来为所有传出的请求设置一些常见的用户代理。
我想我可以做一些

OkHttpClient client = new OkHttpClient();
client.setDefaultUserAgent(...)

...但没有这样的方法或类似的方法。当然我可以提供一些扩展实用程序方法,它将 Package 一个RequestBuilder来附加.header("UserAgent"),然后我将使用它来构建我所有的请求,但我想也许我错过了一些现有的和更简单的方法?

uz75evzq

uz75evzq1#

您可以使用拦截器将User-Agent标头添加到所有请求中。
有关okHttp拦截器的更多信息,请参见http://square.github.io/okhttp/interceptors/
此拦截器的示例实现:

/* 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);
    }
}

用户代理拦截器的测试:

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"));
}
ohfgkhjo

ohfgkhjo2#

如果有人正在寻找这个与OkHttp 3和在Kotlin工作:

val client = OkHttpClient.Builder()
    .addNetworkInterceptor { chain ->
      chain.proceed(
          chain.request()
              .newBuilder()
              .header("User-Agent", "COOL APP 9000")
              .build()
      )
    }
    .build()
7uhlpewt

7uhlpewt3#

okHttp v2.1将在接下来的几周内发布,如果还没有设置的话,will automatically set将是User-Agent的头部。
到目前为止,还没有一个好的方法可以集中地将这个头添加到每个请求中,唯一的解决办法是为每个创建的Request手动添加这个头。

vltsax25

vltsax254#

根据@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);
    }
}

加上更新的测试:

@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"));
}
htzpubme

htzpubme5#

您必须在较新版本中使用builder。***(2021年9月)***

client = new OkHttpClient.Builder()
            .addInterceptor(new Interceptor() {
                @NotNull
                @Override
                public Response intercept(@NotNull Chain chain) throws IOException {
                    Request originalRequest = chain.request();
                    Request requestWithUserAgent = originalRequest.newBuilder()
                            .header("User-Agent", "My Agent is so cool")
                            .build();
                    return chain.proceed(requestWithUserAgent);
                }
            })
            .build();
kzipqqlq

kzipqqlq6#

在新版本的OkHttp中不再需要使用拦截器。添加用户代理非常简单:

Request request = new Request.Builder()
    .url("http://www.publicobject.com/helloworld.txt")
    .header("User-Agent", "OkHttp Example")
    .build();

来源:OkHttp wiki

noj0wjuj

noj0wjuj7#

和Kotlin一起加入拦截器

private val client = OkHttpClient.Builder()
   .addInterceptor(object: Interceptor{
       override fun intercept(chain: Interceptor.Chain): Response {
           val request = chain.request()
           val reqBuilder = request.newBuilder()
               .header("Accept-Language", Locale.getDefault().language)
               .header("User-Agent", "New User-Agent String")
           return chain.proceed(reqBuilder.build())
       }
   })
  .build()

private val retrofit: Retrofit = Retrofit.Builder()
   .baseUrl(Constants.BASE_URL)
   .client(client)
   .addConverterFactory(GsonConverterFactory.create())
   .build()

相关问题