
HttpClient定义
HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包。
HttpClient作用
HTTP Client和浏览器有点像,都可以用来发送请求,接收服务端响应的数据,但它不是浏览器,没有用户界面,只通过其API用于传输和接受HTTP消息。
HttpClient功能
HttpClient的主要功能,包含如下:
- 基于标准的java语言实现了Http1.0和Http1.1等;
- 实现了所有 HTTP 的方法,比如:GET、POST、PUT、HEAD、DELETE、HEAD、OPTIONS 等;
- 支持 HTTPS 协议;
- 支持代理服务器,比如:Nginx等;
- 支持自动跳转转向等;
HttpClient使用步骤
使用HttpClient发送请求接收响应很简单,一般需要如下六步即可:
第一步: 创建HttpClient对象
CloseableHttpClient HttpClient = HttpClientBuilder.create().build();
提示:推荐用CloseableHttpClient,HttpClient是历史遗留版本,官方推荐使用CloseableHttpClient。
第二步:创建请求方法的实例,并指定请求URL。
如果需要发送GET请求,创建HttpGet对象。
HttpGet httpGet = new HttpGet("https://mikechen.cc");
如果需要发送POST请求,创建HttpPost对象。
HttpPost httppost = new HttpPost("https://mikechen.cc");
第三步:设置发送请求参数
如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HttpParams params)方法来添加请求参数。
第四步:调用execute发送请求
HttpResponse response = HttpClient.execute(httpGet);
发送请求,该方法返回一个HttpResponse。
第五步:获取请求内容
调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。
//调用HttpResponse的getEntity()方法可获取HttpEntity对象 HttpEntity resEntity = response.getEntity();
调用HttpResponse的getEntity()方法,程序可通过该对象获取服务器的响应内容。
第六步:释放连接
response.close(); HttpClient.close();
无论执行方法是否成功,都必须释放连接。
HttpClient使用实例
下面我们一起再看下完整的HttpClient使用实例。
1.添加HttpClient依赖
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/HttpClient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>HttpClient</artifactId>
<version>5.2</version>
</dependency>
2.发送GET请求
HttpClient发送GET请求的例子,如下所示:
public void doGetTestOne() {
// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
CloseableHttpClient HttpClient = HttpClientBuilder.create().build();
// 创建Get请求
HttpGet httpGet = new HttpGet("https://mikechen.cc/item/1/31661");
// 响应模型
CloseableHttpResponse response = null;
try {
// 由客户端执行(发送)Get请求
response = HttpClient.execute(httpGet);
// 从响应模型中获取响应实体
HttpEntity responseEntity = response.getEntity();
System.out.println("响应状态为:" + response.getStatusLine());
if (responseEntity != null) {
System.out.println("响应内容长度为:" + responseEntity.getContentLength());
System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 释放资源
if (HttpClient != null) {
HttpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
GET请求的参数传递是通过URL拼接来实现的,所以,我们想发送带参数的Get请求,可直接拼接在ulr后。
3.发送POST请求
/*
* 封装HttpClient发送post请求的工具类
* */
public class HttpClientUtils {
//私有化构造器,防止HttpClientUtils被创建对象
private HttpClientUtils(){
}
static CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
//HttpPost的请求执行
public static String sendHttpPost(String url, JSONObject JsonValues) throws UnsupportedEncodingException {
HttpClientUtils = HttpClientUtils.getHttpClientUtils();
//获取HttpPost
HttpPost httpPost = new HttpPost(url);
//设置请求头
httpPost.setHeader("x-appid", "test");
httpPost.setHeader("x-client-version", "4.0.0");
httpPost.setHeader("Content-Type","application/json");
// 设置请求体
StringEntity entity = new StringEntity(JsonValues.toString());
httpPost.setEntity(entity);
String content = null;
try {
CloseableHttpResponse responseTest = closeableHttpClient.execute(httpPost);
if (responseTest.getStatusLine().getStatusCode() == 200) {
// 获取响应实体
HttpEntity resTestEntity = responseTest.getEntity();
// 输出响应
content = EntityUtils.toString(resTestEntity, "utf-8");
}else {
System.out.println("无效请求");
}
responseTest.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
closeableHttpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
return content;
}
}
mikechen睿哥
10年+一线大厂架构实战经验,就职于阿里、淘宝等一线大厂,操盘多个亿级大厂核心项目。