国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

OkHttp如何移除User-Agent,Accept-Encoding等框架自動(dòng)添加的請(qǐng)求頭參數(shù)

newsning / 3879人閱讀

摘要:移除頭部參數(shù)然后再將自定義的攔截器設(shè)置為網(wǎng)絡(luò)攔截器信任所有證書設(shè)置應(yīng)用攔截器無(wú)效,因?yàn)槭窃趹?yīng)用攔截器之后添加的這樣就能達(dá)到移除自動(dòng)添加的請(qǐng)求頭參數(shù)的目的了。

使用OkHttp網(wǎng)絡(luò)框架在進(jìn)行網(wǎng)絡(luò)請(qǐng)求時(shí)會(huì)發(fā)現(xiàn),傳到后臺(tái)的請(qǐng)求頭中會(huì)比我們自己添加的參數(shù)多出幾個(gè)額外參數(shù)。查看源碼會(huì)發(fā)現(xiàn)

 private Response getResponseWithInterceptorChain() throws IOException {
    // Build a full stack of interceptors.
    List 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會(huì)默認(rèn)添加一個(gè)橋接攔截器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 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中會(huì)默認(rèn)添加User-Agent,Accept-Encoding等請(qǐng)求頭參數(shù)。有時(shí)候我們并不需要這些默認(rèn)添加的參數(shù),那么我們?nèi)绾尾拍茏龅揭瞥鼈兡兀?/p>

通過(guò)上面第一段的部分源碼

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內(nèi)部在添加完BridgeInterceptor后,才開始添加networkInterceptors,所以我們需要借助網(wǎng)絡(luò)攔截器來(lái)重新攔截請(qǐng)求頭,并操作頭部參數(shù)。

首先我們要自定義一個(gè)攔截器,在攔截器中移除我們不需要的參數(shù)。

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();
        //移除頭部參數(shù)
        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;
        }
    }

}

然后再將自定義的攔截器設(shè)置為網(wǎng)絡(luò)攔截器

  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> cookieStore = new HashMap<>();

                    @Override
                    public void saveFromResponse(HttpUrl httpUrl, List list) {
                        cookieStore.put(httpUrl.host(), list);
                    }

                    @Override
                    public List loadForRequest(HttpUrl httpUrl) {
                        List cookies = cookieStore.get(httpUrl.host());
                        return cookies != null ? cookies : new ArrayList();
                    }
                });

  NetInterceptor netInterceptor = new NetInterceptor(mbuilder);
  //mOkBuilder.addNetworkInterceptor(netInterceptor);//設(shè)置應(yīng)用攔截器無(wú)效,因?yàn)锽ridgeInterceptor是在應(yīng)用攔截器之后添加的
  mOkBuilder.addNetworkInterceptor(netInterceptor);

這樣就能達(dá)到移除BridgeInterceptor自動(dòng)添加的請(qǐng)求頭參數(shù)的目的了。

文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請(qǐng)注明本文地址:http://specialneedsforspecialkids.com/yun/76479.html

相關(guān)文章

  • RxEasyHttp一款基于RxJava2+Retrofit2實(shí)現(xiàn)簡(jiǎn)單易用網(wǎng)絡(luò)請(qǐng)求框架

    摘要:注和是當(dāng)下非常火爆的開源框架,均來(lái)自神一般的公司。特點(diǎn)比使用更簡(jiǎn)單更易用。默認(rèn)初始化如果使用默認(rèn)始化后,一切采用默認(rèn)設(shè)置。為單個(gè)請(qǐng)求設(shè)置超時(shí),比如涉及到文件的需要設(shè)置讀寫等待時(shí)間多一點(diǎn)。 github源碼地址:https://github.com/zhou-you/RxEasyHttp RxEasyHttp 本庫(kù)是一款基于RxJava2+Retrofit2實(shí)現(xiàn)簡(jiǎn)單易用的網(wǎng)絡(luò)請(qǐng)求框架,結(jié)...

    MadPecker 評(píng)論0 收藏0
  • HTTPie 官方文檔中文翻譯版

    摘要:目標(biāo)是讓與的交互盡可能的更友好。在版本以上已經(jīng)成為了默認(rèn)的版本。不同類型的鍵值對(duì)分割符號(hào)分別是。這將會(huì)協(xié)商服務(wù)端和你安裝的支持的最高協(xié)議版本。 博客原文? HTTPie 是一個(gè)命令行 HTTP 客戶端。目標(biāo)是讓 CLI 與 Web services 的交互盡可能的更友好。它提供了一個(gè)簡(jiǎn)單的 http 命令,可以讓我們用簡(jiǎn)單自然的表述發(fā)送任意 HTTP 請(qǐng)求,并且可以輸出帶代碼高亮的結(jié)果...

    Baaaan 評(píng)論0 收藏0

發(fā)表評(píng)論

0條評(píng)論

最新活動(dòng)
閱讀需要支付1元查看
<