1导入依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.14</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.13</version>
</dependency>
2.编写工具类并调用其中的方法
package com.sgwl.warehouse.util.tool;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sun.el.lang.FunctionMapperFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
/**
* HttpClient工具类
* httpclient.jar
*/
@Slf4j
public class HttpClientUtil {
//编码格式
private static final String ENCODING = "UTF-8";
//连接超时时间(毫秒)
private static final int CONNECT_TIMEOUT = 2000;
//响应时间(毫秒)
private static final int SOCKET_TIMEOUT = 2000;
/**
* 发送get请求(不含header不含参数)
*
* @param url
* @return
* @throws Exception
*/
public static HttpClientModel doGet(String url) throws Exception {
return doGet(url, null, null);
}
/**
* 发送post请求
*
* @param url 路径
* @param jsonObject 参数(json类型)
* @return
* @throws
* @throws IOException
*/
public static String send(String url, JSONObject jsonObject) {
String body = "";
//创建httpclient对象
CloseableHttpClient client = HttpClients.createDefault();
//创建post方式请求对象
HttpPost httpPost = new HttpPost(url);
//装填参数
StringEntity s = new StringEntity(jsonObject.toString(), "utf-8");
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
//设置参数到请求对象中
httpPost.setEntity(s);
System.out.println("请求地址:" + url);
//设置header信息
//指定报文头【Content-type】
httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
//执行请求操作,并拿到结果(同步阻塞)
CloseableHttpResponse response = null;
try {
response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
//按指定编码转换结果实体为String类型
body = EntityUtils.toString(entity, "utf-8");
}
EntityUtils.consume(entity);
//释放链接
response.close();
} catch (IOException e) {
e.printStackTrace();
}
//获取结果实体
return body;
}
public static JSONObject dopostFor(String url, JSONObject param) {
//定义接收数据
JSONObject result = new JSONObject();
HttpPost httpPost = new HttpPost(url);
CloseableHttpClient client = HttpClients.createDefault();
//请求参数转JOSN字符串
StringEntity entity = new StringEntity(param.toString(), "UTF-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
// if (param.toString().length() <= 200) {
// log.info("HttpClientUtil.doPost.url:{}||param:{}", url, param);
// }
try {
HttpResponse response = client.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
result = JSON.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));
}
} catch (IOException e) {
log.info("HttpClientUtil.doPost.url:{}||result:{}", url, result);
e.printStackTrace();
result.put("code", "500");
result.put("error", "连接错误!");
}
return result;
}
public static JSONObject dopost(String url, JSONObject param) {
//定义接收数据
JSONObject result = new JSONObject();
HttpPost httpPost = new HttpPost(url);
CloseableHttpClient client = HttpClients.createDefault();
//请求参数转JOSN字符串
StringEntity entity = new StringEntity(param.toString(), "UTF-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
if (param.toString().length() <= 200) {
log.info("HttpClientUtil.doPost.url:{}||param:{}", url, param);
}
try {
HttpResponse response = client.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
result = JSON.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));
}
log.info("HttpClientUtil.doPost.url:{}||result:{}", url, result);
} catch (IOException e) {
log.info("HttpClientUtil.doPost.url:{}", url, e);
result.put("code", "500");
result.put("error", "连接错误!");
}
return result;
}
public static JSONObject dopostForm1(String url, JSONObject param) {
JSONObject result = new JSONObject();
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost(url);
MultipartEntity entity = new MultipartEntity();
for (String key : param.keySet()) {
String value = param.getString(key);
entity.addPart(key, new StringBody(value, ContentType.TEXT_PLAIN));
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String responseBody = EntityUtils.toString(response.getEntity());
result = JSON.parseObject(responseBody);
}
log.info("HttpClientUtil.doPost.url:{}||result:{}", url, result);
} catch (IOException e) {
e.printStackTrace();
result.put("code", "500");
result.put("error", "连接错误!");
}
return result;
}
public static JSONObject dopostForm(String url, JSONObject param) {
//定义接收数据
JSONObject result = new JSONObject();
HttpPost httpPost = new HttpPost(url);
CloseableHttpClient client = HttpClients.createDefault();
//请求参数转JOSN字符串
StringEntity entity = new StringEntity(param.toString(), "UTF-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("multipart/form-data; boundary=<calculated when request is sent>");
httpPost.setEntity(entity);
// String boundary = "YOUR_BOUNDARY_VALUE"; // 用自定义的边界标识符替换 YOUR_BOUNDARY_VALUE
// entity.setContentType("multipart/form-data; boundary=" + boundary);
if (param.toString().length() <= 200) {
log.info("HttpClientUtil.doPost.url:{}||param:{}", url, param);
}
try {
HttpResponse response = client.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
result = JSON.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));
}
log.info("HttpClientUtil.doPost.url:{}||result:{}", url, result);
} catch (IOException e) {
e.printStackTrace();
result.put("code", "500");
result.put("error", "连接错误!");
}
return result;
}
/**
* 发送get请求(不含header含参数)
*
* @param url
* @param param
* @return
* @throws Exception
*/
public static HttpClientModel doGet(String url, Map<String, String> param) throws Exception {
return doGet(url, null, param);
}
/**
* 发送get请求(含header含参数)
*
* @param url
* @param header
* @param param
* @return
* @throws Exception
*/
public static HttpClientModel doGet(String url, Map<String, String> header, Map<String, String> param) throws Exception {
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
URIBuilder uriBuilder = new URIBuilder(url);
if (param != null) {
Set<Map.Entry<String, String>> entrySet = param.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
uriBuilder.setParameter(entry.getKey(), entry.getValue());
}
}
HttpGet httpGet = new HttpGet(uriBuilder.build());
RequestConfig requestConfig = RequestConfig
.custom()
.setConnectTimeout(CONNECT_TIMEOUT)
.setSocketTimeout(SOCKET_TIMEOUT)
.build();
httpGet.setConfig(requestConfig);
/**
* 封装header
*/
packageHeader(header, httpGet);
CloseableHttpResponse closeableHttpResponse = null;
try {
/**
* 发送请求获取响应
*/
return getHttpClientResult(closeableHttpResponse, closeableHttpClient, httpGet);
} finally {
/**
* 关闭资源
*/
close(closeableHttpResponse, closeableHttpClient);
}
}
/**
* 发送post请求(不含header不含参数)
*
* @param url
* @return
* @throws Exception
*/
public static HttpClientModel doPost(String url) throws Exception {
return doPost(url, null, null);
}
/**
* 发送post请求(含header不含参数)
*
* @param url
* @param param
* @return
* @throws Exception
*/
public static HttpClientModel doPost(String url, Map<String, String> param) throws Exception {
return doPost(url, null, param);
}
/**
* 发送post请求(含header含参数)
*
* @param url
* @param header
* @param param
* @return
* @throws Exception
*/
public static HttpClientModel doPost(String url, Map<String, String> header, Map<String, String> param) throws Exception {
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig
.custom()
.setConnectTimeout(CONNECT_TIMEOUT)
.setSocketTimeout(SOCKET_TIMEOUT)
.build();
httpPost.setConfig(requestConfig);
/**
* 设置header
*/
// httpPost.setHeader("Cookie", "");
httpPost.setHeader("Connection", "keep-alive");
httpPost.setHeader("Accept", "application/json");
// httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
// httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");
/**
* 封装header
*/
packageHeader(header, httpPost);
/**
* 封装参数
*/
packageParam(param, httpPost);
CloseableHttpResponse closeableHttpResponse = null;
try {
/**
* 发送请求获取响应
*/
return getHttpClientResult(closeableHttpResponse, closeableHttpClient, httpPost);
} finally {
/**
* 关闭资源
*/
close(closeableHttpResponse, closeableHttpClient);
}
}
/**
* 发送put请求(不含header不含参数)
*
* @param url
* @return
* @throws Exception
*/
public static HttpClientModel doPut(String url) throws Exception {
return doPut(url);
}
/**
* 发送put请求(不含header含参数)
*
* @param url
* @param param
* @return
* @throws Exception
*/
public static HttpClientModel doPut(String url, Map<String, String> param) throws Exception {
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
HttpPut httpPut = new HttpPut(url);
RequestConfig requestConfig = RequestConfig
.custom()
.setConnectTimeout(CONNECT_TIMEOUT)
.setSocketTimeout(SOCKET_TIMEOUT)
.build();
httpPut.setConfig(requestConfig);
/**
* 封装参数
*/
packageParam(param, httpPut);
CloseableHttpResponse closeableHttpResponse = null;
try {
/**
* 发送请求获取响应
*/
return getHttpClientResult(closeableHttpResponse, closeableHttpClient, httpPut);
} finally {
/**
* 关闭资源
*/
close(closeableHttpResponse, closeableHttpClient);
}
}
/**
* 发送delete请求(不含header不含参数)
*
* @param url
* @return
* @throws Exception
*/
public static HttpClientModel doDelete(String url) throws Exception {
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
HttpDelete httpDelete = new HttpDelete(url);
RequestConfig requestConfig = RequestConfig
.custom()
.setConnectTimeout(CONNECT_TIMEOUT)
.setSocketTimeout(SOCKET_TIMEOUT)
.build();
httpDelete.setConfig(requestConfig);
CloseableHttpResponse closeableHttpResponse = null;
try {
/**
* 发送请求获取响应
*/
return getHttpClientResult(closeableHttpResponse, closeableHttpClient, httpDelete);
} finally {
/**
* 关闭资源
*/
close(closeableHttpResponse, closeableHttpClient);
}
}
/**
* 发送delete请求(不含header含参数)
*
* @param url
* @param param
* @return
* @throws Exception
*/
public static HttpClientModel doDelete(String url, Map<String, String> param) throws Exception {
if (null == param) {
param = new HashMap<String, String>();
}
param.put("_method", "delete");
return doPost(url, param);
}
/**
* 封装header
*
* @param param
* @param httpRequestBase
*/
public static void packageHeader(Map<String, String> param, HttpRequestBase httpRequestBase) {
if (param != null) {
Set<Map.Entry<String, String>> entrySet = param.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
httpRequestBase.setHeader(entry.getKey(), entry.getValue());
}
}
}
/**
* 封装参数
*
* @param param
* @param httpEntityEnclosingRequestBase
* @throws Exception
*/
public static void packageParam(Map<String, String> param, HttpEntityEnclosingRequestBase httpEntityEnclosingRequestBase) throws Exception {
if (param != null) {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
Set<Map.Entry<String, String>> entrySet = param.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
httpEntityEnclosingRequestBase.setEntity(new UrlEncodedFormEntity(nameValuePairs, ENCODING));
}
}
/**
* 获取响应
*
* @param closeableHttpResponse
* @param closeableHttpClient
* @param httpRequestBase
* @return
* @throws Exception
*/
public static HttpClientModel getHttpClientResult(CloseableHttpResponse closeableHttpResponse
, CloseableHttpClient closeableHttpClient
, HttpRequestBase httpRequestBase) throws Exception {
closeableHttpResponse = closeableHttpClient.execute(httpRequestBase);
if (closeableHttpResponse != null && closeableHttpResponse.getStatusLine() != null) {
String content = "";
if (closeableHttpResponse.getEntity() != null) {
content = EntityUtils.toString(closeableHttpResponse.getEntity(), ENCODING);
}
return new HttpClientModel(closeableHttpResponse.getStatusLine().getStatusCode(), content);
}
return new HttpClientModel(HttpStatus.SC_INTERNAL_SERVER_ERROR);
}
/**
* 关闭资源
*
* @param closeableHttpResponse
* @param closeableHttpClient
* @throws Exception
*/
public static void close(CloseableHttpResponse closeableHttpResponse, CloseableHttpClient closeableHttpClient) throws Exception {
if (closeableHttpResponse != null) {
closeableHttpResponse.close();
}
if (closeableHttpClient != null) {
closeableHttpClient.close();
}
}
}
其中使用的是
public static JSONObject dopostForm1(String url, JSONObject param) {
JSONObject result = new JSONObject();
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost(url);
MultipartEntity entity = new MultipartEntity();
for (String key : param.keySet()) {
String value = param.getString(key);
entity.addPart(key, new StringBody(value, ContentType.TEXT_PLAIN));
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String responseBody = EntityUtils.toString(response.getEntity());
result = JSON.parseObject(responseBody);
}
log.info("HttpClientUtil.doPost.url:{}||result:{}", url, result);
} catch (IOException e) {
e.printStackTrace();
result.put("code", "500");
result.put("error", "连接错误!");
}
return result;
}
@Override
public JSONObject outOrderConfirm(String id, String[] rfIds) throws UnsupportedEncodingException {
JSONObject param = new JSONObject();
param.put("id", id);
param.put("rfids", rfIds);
return HttpClientUtil
.dopostForm1(outEsIcBaseUrl + "ic/outOrderConfirm", param);
}