天天看点

[通用解决方案]--(2)Post请求发送Json格式的body体工具类

Author:赵志乾
Date:2019-08-29
Declaration:All Right Reserved!!!
           

场景

当前服务需要调用其他服务提供的基于http的接口。要求使用Post操作,Content-Type为application/json,字符集编码为UTF-8

解决方案

引用的jar包

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.5</version>
</dependency>
       
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5</version>
</dependency>
           

工具类代码:

public class HttpClientUtil {
    private static HttpClientBuilder httpClientBuilder;
    private static Logger log;
    static {
        log = LoggerFactory.getLogger(HttpClientUtil.class);
        httpClientBuilder = HttpClientBuilder.create();
    }

    /**
     * 发送post请求
     * @param url  请求的url
     * @param body json串
     * @return
     */
    public static String sendPostJsonBody(String url, String body) {
        log.debug("[HttpClientUtil][sendPostJsonBody] 入参 url={} body={}", url, body);

        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json;charset=utf-8");
        StringEntity entity = new StringEntity(body, "utf-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);

        try {
            HttpClient client = httpClientBuilder.build();
            HttpResponse response = client.execute(httpPost);
            if (response.getStatusLine() != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String result = EntityUtils.toString(response.getEntity(), "utf-8");
                log.debug("[HttpClientUtil][sendPostJsonBody] 结果 url={} result={}", url, result);
                return result;
            }
            log.warn("[HttpClientUtil][sendPostJsonBody] 请求失败 response={}", url, response.toString());
            return "";
        }
        catch (IOException ex) {
            log.error("[HttpClientUtil][sendPostJsonBody] 请求异常 ex={}", url, ex);
            return "";
        }
    }
}
           

继续阅读