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

}

你可能感兴趣的:(HTTP工具类)