首页 > 代码库 > httpclient 4.x使用
httpclient 4.x使用
httpclient-4.x.x版本进行了升级,和3.x.x有些区别。下面主要介绍下简单的使用get与post方法发送HTTP请求。
直接上代码,GET方法:
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
//ConnectTimeout:建立连接时超时时间;SocketTimeout:socket建立连接后等待数据时间;
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(100).setConnectTimeout(100)
.setSocketTimeout(100).build();
HttpResponse httpResponse = null;
try {
HttpGet httpGet = new HttpGet("http://www.mysite.com");
// 添加head方法一
httpGet.addHeader("User-Agent",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36");
// 添加head方法二
httpGet.addHeader(new BasicHeader("Accept-Language", "zh-CN,zh;q=0.8"));
httpGet.setConfig(requestConfig);
httpResponse = httpClient.execute(httpGet);
String html = EntityUtils.toString(httpResponse.getEntity(), "gbk");
System.out.println(html);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
下面是POST方法,里面设置参数的方法与GET一样,就补详细写了:
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
//ConnectTimeout:建立连接时超时时间;SocketTimeout:socket建立连接后等待数据时间;
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(100).setConnectTimeout(100)
.setSocketTimeout(100).build();
List<NameValuePair> list = new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("key", "value"));
HttpEntity httpEntiry = null;
HttpResponse httpResponse = null;
try {
httpEntiry = new UrlEncodedFormEntity(list);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
HttpPost httpPost = new HttpPost("http://www.mysite.com");
httpPost.setEntity(httpEntiry);
httpPost.setConfig(requestConfig);
try {
httpResponse = httpClient.execute(httpPost);
System.out.println(EntityUtils.toString(httpResponse.getEntity(), "gbk"));
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
使用的一些小经验:
当你访问一个网页的时候,网页可能会返回一些cookie信息,httpClient会自动设置在对象中。例如:模拟登陆的时候,先使用get的方式请求登陆页,这样httpclient会保持一些cookie信息,然后使用post的方式带上参数去模拟登陆,成功;如果省略掉get请求登陆页,直接post,失败,所以有些时候需要保持这个httpclient对象来方便进行下一步的操作。透露一下,可以使用PoolingHttpClientConnectionManager进行httpclient的管理。
httpclient 4.x使用