1.简介
HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,
2.主要功能
- 实现了所有 HTTP 的方法(GET,POST,PUT,HEAD 等)
- 支持自动转向
- 支持 HTTPS 协议
- 支持代理服务器等
3.执行get请求
不带参数
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建http GET请求
HttpGet httpGet = new HttpGet("http://www.baidu.com/");
//创建响应
CloseableHttpResponse response = null;
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
//读取响应内容
String content =EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println("内容长度:" + content.length());
//将内容写到文件中
//FileUtils.writeStringToFile(new File("C:\\baidu.html"), content);
}
带参数
// 定义请求的参数
/*
多个参数
URIBuilder builder = new URIBuilder(url); /String url.
builder.addParameter(key,value));
URI uri = builder.build();
*/
URI uri = new URIBuilder("http://www.baidu.com/s").setParameter("wd", "java").build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
4.执行post请求
不带参数
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建http POST请求
HttpPost httpPost = new HttpPost("http://www.oschina.net/");
CloseableHttpResponse response = null;
// 执行请求
response = httpclient.execute(httpPost);
// 判断返回状态是否为200
if(response.getStatusLine().getStatusCode() == 200) {
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(content);
}
带参数
// 设置2个post参数,一个是scope、一个是q
List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
parameters.add(new BasicNameValuePair(key, value));
// 构造一个form表单式的实体
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
// 将请求实体设置到httpPost对象中,模拟表单
httpPost.setEntity(formEntity);