HttpClient一个开源的Java库用于发送HTTP请求和处理HTTP响应。它提供了一种简洁的方式来执行HTTP通信,并支持各种HTTP方法(如GET、POST、PUT、DELETE等),处理请求和响应的头部、实体和状态等。HttpClient可以用于构建Web应用程序、爬虫、客户端等,使得与HTTP相关的任务更加方便、灵活和高效。
HttpClient在springboot项目中只要的作用就是在方法内发送请求,此些请求一般为get和post类型的请求。
导入依赖
因为aliOss的依赖的底层依赖就是HttpClient所以我们可以直接使用Oss的依赖就可以。
com.aliyun.oss
aliyun-sdk-oss
3.10.2
com.alibaba
fastjson
1.2.76
创建HttpClient的工具类。
import com.alibaba.fastjson.JSONObject;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Http工具类
*/
public class HttpClientUtil {
static final int TIMEOUT_MSEC = 5 * 1000;
/**
* 发送GET方式请求
* @param url
* @param paramMap
* @return
*/
public static String doGet(String url,Map paramMap){
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
String result = "";
CloseableHttpResponse response = null;
try{
URIBuilder builder = new URIBuilder(url);
if(paramMap != null){
for (String key : paramMap.keySet()) {
builder.addParameter(key,paramMap.get(key));
}
}
URI uri = builder.build();
//创建GET请求
HttpGet httpGet = new HttpGet(uri);
//发送请求
response = httpClient.execute(httpGet);
//判断响应状态
if(response.getStatusLine().getStatusCode() == 200){
result = EntityUtils.toString(response.getEntity(),"UTF-8");
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
response.close();
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
* 发送POST方式请求
* 参数携在路径中
* @param url
* @param paramMap
* @return
* @throws IOException
*/
public static String doPost(String url, Map paramMap) throws IOException {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (paramMap != null) {
List paramList = new ArrayList();
for (Map.Entry param : paramMap.entrySet()) {
paramList.add(new BasicNameValuePair(param.getKey(), param.getValue()));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
}
httpPost.setConfig(builderRequestConfig());
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (Exception e) {
throw e;
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
/**
* 发送POST方式请求
* 且请求参数为Json类型。@RequsetParam
* @param url
* @param paramMap
* @return
* @throws IOException
*/
public static String doPost4Json(String url, Map paramMap) throws IOException {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
if (paramMap != null) {
//构造json格式数据
JSONObject jsonObject = new JSONObject();
for (Map.Entry param : paramMap.entrySet()) {
jsonObject.put(param.getKey(),param.getValue());
}
StringEntity entity = new StringEntity(jsonObject.toString(),"utf-8");
//设置请求编码
entity.setContentEncoding("utf-8");
//设置数据类型
entity.setContentType("application/json");
httpPost.setEntity(entity);
}
httpPost.setConfig(builderRequestConfig());
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (Exception e) {
throw e;
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
private static RequestConfig builderRequestConfig() {
return RequestConfig.custom()
.setConnectTimeout(TIMEOUT_MSEC)
.setConnectionRequestTimeout(TIMEOUT_MSEC)
.setSocketTimeout(TIMEOUT_MSEC).build();
}
}
在该工具类中,存在两个请求方式,Get,Post,在post中又存在两个方法,一个方法表示参数在路径中,还有个方法表示参数是一个参数体(Json类型)。
测试
当然我们也可以使用HttpClient原生来发送Get/post请求,工具类中本质的原理就是以下代码。
原生写法:
(http://localhost:8080/admin/employee/login 是一个编写好的用户登录接口)
@Test
public void test3() throws Exception{
//创建httpClients
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建Post请求
HttpPost httpPost = new HttpPost("http://localhost:8080/admin/employee/login");
JSONObject jsonObject = new JSONObject();
jsonObject.put("username", "admin");
jsonObject.put("password", "123456");
StringEntity stringEntity = new StringEntity(jsonObject.toString());
stringEntity.setContentType("application/json");
stringEntity.setContentEncoding("utf-8");
httpPost.setEntity(stringEntity);
CloseableHttpResponse response = httpClient.execute(httpPost);
System.out.println("状态码为:" + response.getStatusLine().getStatusCode());
System.out.println(response.getEntity().getContent());
System.out.println(EntityUtils.toString(response.getEntity()));
httpClient.close();
response.close();
}
使用上述工具类的静态方法实现步骤为下:
@Test
public void test4() throws Exception{
HashMap stringObjectHashMap = new HashMap<>();
stringObjectHashMap.put("username", "admin");
stringObjectHashMap.put("password", "123456");
String s = HttpClientUtil.doPost4Json("http://localhost:8080/admin/employee/login", stringObjectHashMap);
System.out.println(s);
}
后续使用HttpClient是只需要引入HttpClientUtil即可,其代码是固定的,在springBoot项目的Controller方法中,在内部发送请求也就发送Get/Post情况最多,一般就是查询数据和提交数据。