How to specify a default user agent for okhttp 2.x requests

后端 未结 6 1453
心在旅途
心在旅途 2021-01-31 02:01

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



        
6条回答
  •  情话喂你
    2021-01-31 02:37

    Based on @josketres answer, here is a similar Interceptor for OkHttp version 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"));
    }
    

提交回复
热议问题