HttpClient是Apache的子项目,可以用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并支持HTTP协议最新的版本和建议。
HttpClient提供的主要的功能:
1、实现了所有的HTTP的方法(GET、POST、PUT、DELETE等)
2、支持自动转向
3、支持HTTPS协议
4、支持代理服务器等
GET请求:
public static void main(String[] args) throws Exception {
// 创建Httpclient对象 == 打开浏览器
CloseableHttpClient httpclient = HttpClients.createDefault();
// 定义请求的参数 ==浏览器输入路径url
URI uri = new URIBuilder("...url...").setParameter("wd", "java").setParameter("td", "php").build();
System.out.println(uri);
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
CloseableHttpResponse response = null;
try {
// 发送请求 == 按回车,发出请求,并封装响应
response = httpclient.execute(httpGet);
// 状态码,和内容
System.out.println(response.getStatusLine().getStatusCode());
if (response.getEntity() != null) {
String body = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(body);
}
} finally {
if (response != null) {
response.close();
}
// == 关闭浏览器
httpclient.close();
}
}
POST请求:
public static void main(String[] args) throws Exception {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建http POST请求
HttpPost httpPost = new HttpPost("...url...");
// {{{ 设置 参数
List<NameValuePair> parameters = new ArrayList<NameValuePair>(10);
parameters.add(new BasicNameValuePair("title", "HttpClient操作测试"));
// 构造一个form表单的实体
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters,"UTF-8");
// 将请求实体设置到httpPost对象中 }}} <------没有参数 不用写
httpPost.setEntity(formEntity);
CloseableHttpResponse response = null;
try {
// 执行请求
response = httpclient.execute(httpPost);
// 状态码和内容
System.out.println(response.getStatusLine().getStatusCode());
if (response.getEntity() != null) {
String body = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(body);
}
} finally {
if (response != null) {
response.close();
}
httpclient.close();
}
}
PUT请求方式,与POST方式类似,不同点在于API:
post是HttpPost,而put是HttpPut。
DELETE请求方式,与GET方式类似,不同点在于API:
get是HttpGet,而delete是HttpDelete。
待续……