九江網(wǎng)站建設(shè)優(yōu)化公司營銷的方法手段有哪些
2019獨角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>
簡要
這個簡易手冊將告訴我們Apache HttpClient 4 的一些使用示例。 在這里主要是講HttpClient 4.3.x或以上的版本的使用事例。在一些老版本中可能是無法使用的。 以下的示例。只是功能的實現(xiàn),沒有詳細(xì)的說明和必要的解釋。
示例
創(chuàng)建HTTP鏈接
CloseableHttpClient client = HttpClientBuilder.create().build();
發(fā)送一個GET請求 instance.execute(new HttpGet("http://www.google.com"));
從HTTP Response中獲取返回狀態(tài) CloseableHttpResponse response = instance.execute(new HttpGet("http://www.google.com"));
assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); 獲取響應(yīng)的媒體類型 CloseableHttpResponse response = instance.execute(new HttpGet("http://www.google.com"));
String contentMimeType = ContentType.getOrDefault(response.getEntity()).getMimeType();
assertThat(contentMimeType, equalTo(ContentType.TEXT_HTML.getMimeType()));
獲取響應(yīng)的body CloseableHttpResponse response = instance.execute(new HttpGet("http://www.google.com"));
String bodyAsString = EntityUtils.toString(response.getEntity());
assertThat(bodyAsString, notNullValue());
配置超時請求 @Test(expected = SocketTimeoutException.class)
public void givenLowTimeout_whenExecutingRequestWithTimeout_thenException() throws ClientProtocolException, IOException {RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(50).setConnectTimeout(50).setSocketTimeout(50).build();HttpGet request = new HttpGet(SAMPLE_URL);request.setConfig(requestConfig);instance.execute(request);
}
配置整個客戶端超市請求 RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(50).setConnectTimeout(50).setSocketTimeout(50).build();
HttpClientBuilder builder = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig);
發(fā)送一個POST請求 instance.execute(new HttpPost(SAMPLE_URL));
request 添加參數(shù) List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("key1", "value1"));
params.add(new BasicNameValuePair("key2", "value2"));
request.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));
HTTP Request 重定向處理 CloseableHttpClient instance = HttpClientBuilder.create().disableRedirectHandling().build();
CloseableHttpResponse response = instance.execute(new HttpGet("http://t.co/I5YYd9tddw"));
assertThat(response.getStatusLine().getStatusCode(), equalTo(301));
配置請求的header CloseableHttpResponse response = instance.execute(new HttpGet(SAMPLE_URL));
Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);
assertThat(headers, not(emptyArray()))
關(guān)閉釋放資源 response = instance.execute(new HttpGet(SAMPLE_URL));
try {HttpEntity entity = response.getEntity();if (entity != null) {InputStream instream = entity.getContent();instream.close();}
} finally {response.close();
}
結(jié)束
所有這些例子都可以在作者的[weblink url="https://github.com/eugenp/tutorials/tree/master/httpclient#readme"]git 項目[/weblink] 里找到.是在eclipse環(huán)境下開發(fā)的。應(yīng)該很容易跑起來
轉(zhuǎn)載于:https://my.oschina.net/u/265943/blog/292898