本文共 3078 字,大约阅读时间需要 10 分钟。
用OKhttp框架请求http请求的时候会把user-agent带上;然而有些时候我们需要把请求头里面的user-agent去掉;
客户端程序:
private static final String BASE_URL = "http://192.168.253.200:8080/Chapter/"; public static void testHeaders() { HttpClient httpClient = new HttpClient.Builder(BASE_URL).isDebug(false) .add("header", "12345") .header("master", "china") .connectTimeout(5000) .readTimeout(5000) .build(); httpClient.Api().send(new HttpClient.Builder().url("postParam") .add("header", "123459") .add("master", "usa") .add("token", "388298a0c89f4a38b2fed4cd4123d441") .method(Method.POST) .build(), new ResultSubscriber<>(new ResultListener
返回结果:
{"headers":{ "content-length":"76", "host":"192.168.253.200:8080", "client":"Android Client", "content-type":"application/x-www-form-urlencoded", "connection":"Keep-Alive", "accept-encoding":"gzip", "master":"china", "user-agent":"okhttp/3.4.1"},"header":"123459","master":"usa","token":"388298a0c89f4a38b2fed4cd4123d441"}
你会发现: “user-agent”:”okhttp/3.4.1” 这是由于okhttp内置拦截器默认添加的。我们需要借助网络拦截器来重新拦截请求头;
利用拦截器来实现对user-agent删除
public class LogInterceptor implements Interceptor {private HttpClient builder;@Overridepublic Response intercept(Chain chain) throws IOException { Request request = chain.request(); request =request.newBuilder().removeHeader("User-Agent").build(); Response response = chain.proceed(request); okhttp3.MediaType mediaType = response.body().contentType(); String content = response.body().string(); return response.newBuilder() .body(okhttp3.ResponseBody.create(mediaType, content)) .build();
然后利用网络拦截器来设置自定义的拦截器LogInterceptor :
Builder okBuilder = new OkHttpClient.Builder() .connectTimeout(mbuilder.getConnectTimeout(), TimeUnit.SECONDS) .readTimeout(mbuilder.getReadTimeout(), TimeUnit.SECONDS) .writeTimeout(mbuilder.getWriteTimeout(), TimeUnit.SECONDS) .sslSocketFactory(OkhttpUtils.createSSLSocketFactory(), new OkhttpUtils. TrustAllCerts())// 信任所有证书 .hostnameVerifier(new OkhttpUtils.TrustAllHostnameVerifier());LogInterceptor logInterceptor = new LogInterceptor(); logInterceptor.setBuilder(mbuilder); //okBuilder.addInterceptor(logInterceptor);//应用拦截器 okBuilder.addNetworkInterceptor(logInterceptor);//网络拦截器
最后重新发送网络请求:
{"headers":{ "content-length":"63", "host":"192.168.253.200:8080", "client":"Android Client", "content-type":"application/x-www-form-urlencoded", "connection":"Keep-Alive", "accept-encoding":"gzip", "master":"china"},"header":"123459","master":"usa","token":"388298a0c89f4a38b2fed4cd4123d441"}
说明:接口postParam是返回请求所有参数和请求头信息。代码就不展示出来了。