/**
* Http请求工具类
*
* @author
*
*/
@Slf4j
public class HttpClientUtil
{
private HttpClientUtil()
{
}
// private static Log logger = LogFactory.getLog(HttpClientUtil.class);
/**
* 发送HTTP_POST请求,json格式数据
*
* @param url
* @param body
* @return
* @throws Exception
*/
public static String sendPostByJson(String url, String body) throws Exception {
CloseableHttpClient httpclient = HttpClients.custom().build();
HttpPost post = null;
String resData = null;
CloseableHttpResponse result = null;
try
{
post = new HttpPost(url);
HttpEntity entity2 = new StringEntity(body, Consts.UTF_8);
post.setConfig(RequestConfig.custom().setConnectTimeout(30000).setSocketTimeout(30000).build());
post.setHeader("Content-Type", "application/json");
post.setHeader("authorization", "APP_KEYS F6D6EB20-ACA1-44BB-A72D-BC92D01BB07E");
post.setEntity(entity2);
result = httpclient.execute(post);
if (HttpStatus.SC_OK == result.getStatusLine().getStatusCode())
{
resData = EntityUtils.toString(result.getEntity());
}
else
{
throw new Exception(EntityUtils.toString(result.getEntity()));
}
}
finally
{
if (result != null)
{
result.close();
}
if (post != null)
{
post.releaseConnection();
}
httpclient.close();
}
return resData;
}
/**
* 请求的时候
*
*
* @param msg
* @return
* @throws Exception
*/
public static Response httpConnection(Object obj, String msg, String url) throws Exception {
String result = HttpClientUtil.sendPostByJson(url, JSON.toJSONString(obj));
Response response = JSON.parseObject(result, Response.class);
// 根据epc查询货品看是否为正确的epc
if ("success".equals(response.getStatus().toLowerCase()))
{
return response;
}
else
{
// 处理显示失败信息
throw new DreamRuntimeException(response.getMsg());
}
}
}
HTTP工具类
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 前言 在我们日常工作中,我们需要经常和第三方接口进行交互通信,很多时候我们都是使用http协议进行交互,java原...