使用OkHttp網路框架在進行網路請求時會發現,傳到後臺的請求頭中會比我們自己新增的引數多出幾個額外引數。檢視原始碼會發現
private Response getResponseWithInterceptorChain() throws IOException {
// Build a full stack of interceptors.
List<Interceptor> interceptors = new ArrayList<>();
interceptors.addAll(client.interceptors());
interceptors.add(retryAndFollowUpInterceptor);
interceptors.add(new BridgeInterceptor(client.cookieJar()));
interceptors.add(new CacheInterceptor(client.internalCache()));
interceptors.add(new ConnectInterceptor(client));
if (!retryAndFollowUpInterceptor.isForWebSocket()) {
interceptors.addAll(client.networkInterceptors());
}
interceptors.add(new CallServerInterceptor(
retryAndFollowUpInterceptor.isForWebSocket()));
Interceptor.Chain chain = new RealInterceptorChain(
interceptors, null, null, null, 0, originalRequest);
return chain.proceed(originalRequest);
}
複製程式碼
OkHttp會預設新增一個橋接攔截器BridgeInterceptor,檢視BridgeInterceptor的原始碼
MediaType contentType = body.contentType();
if (contentType != null) {
requestBuilder.header("Content-Type", contentType.toString());
}
long contentLength = body.contentLength();
if (contentLength != -1) {
requestBuilder.header("Content-Length", Long.toString(contentLength));
requestBuilder.removeHeader("Transfer-Encoding");
} else {
requestBuilder.header("Transfer-Encoding", "chunked");
requestBuilder.removeHeader("Content-Length");
}
}
if (userRequest.header("Host") == null) {
requestBuilder.header("Host", hostHeader(userRequest.url(), false));
}
if (userRequest.header("Connection") == null) {
requestBuilder.header("Connection", "Keep-Alive");
}
// If we add an "Accept-Encoding: gzip" header field we're responsible for also decompressing
// the transfer stream.
boolean transparentGzip = false;
if (userRequest.header("Accept-Encoding") == null) {
transparentGzip = true;
requestBuilder.header("Accept-Encoding", "gzip");
}
List<Cookie> cookies = cookieJar.loadForRequest(userRequest.url());
if (!cookies.isEmpty()) {
requestBuilder.header("Cookie", cookieHeader(cookies));
}
if (userRequest.header("User-Agent") == null) {
requestBuilder.header("User-Agent", Version.userAgent());
}
複製程式碼
在BridgeInterceptor中會預設新增User-Agent,Accept-Encoding等請求頭引數。有時候我們並不需要這些預設新增的引數,那麼我們如何才能做到移除它們呢?
通過上面第一段的部分原始碼
interceptors.add(retryAndFollowUpInterceptor);
interceptors.add(new BridgeInterceptor(client.cookieJar()));
interceptors.add(new CacheInterceptor(client.internalCache()));
interceptors.add(new ConnectInterceptor(client));
if (!retryAndFollowUpInterceptor.isForWebSocket()) {
interceptors.addAll(client.networkInterceptors());
}
複製程式碼
可以看到OkHttp內部在新增完BridgeInterceptor後,才開始新增networkInterceptors,所以我們需要藉助網路攔截器來重新攔截請求頭,並操作頭部引數。
首先我們要自定義一個攔截器,在攔截器中移除我們不需要的引數。
public class NetInterceptorimplements Interceptor {
private HttpClient builder;
public NetInterceptor() {
super();
}
public NetInterceptor(HttpClient builder) {
this.builder = builder;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
//移除頭部引數
request = request.newBuilder()
.removeHeader("User-Agent")
.removeHeader("Accept-Encoding")
.build();
Response response = chain.proceed(request);
if (response.body() != null && response.body().contentType() != null) {
MediaType mediaType = response.body().contentType();
String content = response.body().string();
ResponseBody responseBody = ResponseBody.create(mediaType, content);
return response.newBuilder().body(responseBody).build();
} else {
return response;
}
}
}
複製程式碼
然後再將自定義的攔截器設定為網路攔截器
mOkBuilder = new Builder()
.connectTimeout(mbuilder.getConnectTimeout(), TimeUnit.SECONDS)
.readTimeout(mbuilder.getReadTimeout(), TimeUnit.SECONDS)
.writeTimeout(mbuilder.getWriteTimeout(), TimeUnit.SECONDS)
.sslSocketFactory(createSSLSocketFactory(), new TrustAllCerts())// 信任所有證書
.hostnameVerifier(new TrustAllHostnameVerifier())
.cookieJar(new CookieJar() {
private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();
@Override
public void saveFromResponse(HttpUrl httpUrl, List<Cookie> list) {
cookieStore.put(httpUrl.host(), list);
}
@Override
public List<Cookie> loadForRequest(HttpUrl httpUrl) {
List<Cookie> cookies = cookieStore.get(httpUrl.host());
return cookies != null ? cookies : new ArrayList<Cookie>();
}
});
NetInterceptor netInterceptor = new NetInterceptor(mbuilder);
//mOkBuilder.addNetworkInterceptor(netInterceptor);//設定應用攔截器無效,因為BridgeInterceptor是在應用攔截器之後新增的
mOkBuilder.addNetworkInterceptor(netInterceptor);
複製程式碼
這樣就能達到移除BridgeInterceptor自動新增的請求頭引數的目的了。