如何为okhttp 2.x请求指定默认用户代理 [英] How to specify a default user agent for okhttp 2.x requests

查看:267
本文介绍了如何为okhttp 2.x请求指定默认用户代理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Android应用中使用的是okhttp 2.0,但找不到为所有传出请求设置一些通用用户代理的方法.

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.

我以为我可以做类似的事情

I thought I could do something like

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

...但是没有这种方法或类似方法. 当然,我可以提供一些扩展实用程序方法,该方法将包装一个RequestBuilder并附加.header("UserAgent"),然后将其用于构建所有请求,但我想我可能错过了一些现有且更简单​​的方法?

...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?

推荐答案

您可以使用拦截器将User-Agent标头添加到所有请求中.

You can use an interceptor to add the User-Agent header to all your requests.

有关okHttp拦截器的更多信息,请参见 http://square.github.io/okhttp/interceptors/

For more information about okHttp interceptors see 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);
    }
}

测试UserAgentInterceptor:

Test for the 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"));
}

这篇关于如何为okhttp 2.x请求指定默认用户代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆