天天看點

[通用解決方案]--(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 "";
        }
    }
}
           

繼續閱讀