Cookie rejected Warning While calling Rest API using Java

httpclient 建立的http請求無需傳遞cookie值,結果log中出現大量的warn信息:

[WARN ]13:32:00,828, pool-1-thread-9, [Class]ResponseProcessCookies, Cookie rejected: “[version: 0][name: NTESLOFTSI][value: 9C5DD68981E435146CE7654DBE5107E1.bje3b11-8010][domain: .www.lofter.com][path: /][expiry: null]”.

查看了一些資料,大意是httpclient請求預設需要傳cookie的,那麼是否有辦法忽略cookie的處理呢。

 

有問題的代碼如下:

CloseableHttpClient client = HttpClients.createDefault(); 
HttpGet request = new HttpGet(url); 
CloseableHttpResponse response = client.execute(request);

 

解法如下:

RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES).build(); 
CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(globalConfig).build(); 
HttpGet request = new HttpGet(url); 
CloseableHttpResponse response = client.execute(request);

 

如果你有需要乎略自Sign的SSL 憑證請服用下面這一個 block:

builder.loadTrustMaterial(null, new TrustStrategy() {

@Override

public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {

returntrue;

}

});

X509HostnameVerifierverifier;

verifier = new X509HostnameVerifier() {

@Override

public boolean verify(String hostname, SSLSession session) {

returntrue;

}

@Override

public void verify(String arg0, String[] arg1, String[] arg2) throws SSLException {

}

@Override

public void verify(String arg0, X509Certificate arg1) throws SSLException {

}

@Override

public void verify(String arg0, SSLSocket arg1) throws IOException {

}

};

SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(), verifier);

RequestConfigglobalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES).build(); 

CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(globalConfig).setSSLSocketFactory(sslsf).build(); 

 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *