HTTP工具类

/**
 * 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());
        }
    }

}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.添加maven依赖 2.HttpUtils(POST GET) 3.测试
    jsjack_wang阅读 449评论 0 0
  • public static final StringDEF_CHATSET ="UTF-8"; public s...
    Jetlag时阅读 625评论 0 0
  • 前言 在我们日常工作中,我们需要经常和第三方接口进行交互通信,很多时候我们都是使用http协议进行交互,java原...
    liangzzz阅读 14,611评论 1 11
  • 有人说自己用随手记三年,却没有从记账中获益。 希望这篇文章能改变他们的看法,让记账成为他们成功理财的第一步。 记账...
    理财师小V阅读 601评论 4 10
  • 暑假,我去超市打工,推销蓝月亮。本来我想去我们那一家特有品味的咖啡店的,可惜我们暑假放的比较晚,基本上找不到兼职...
    五味lucky阅读 465评论 0 2