http发送url请求

public class HttpUtils {
    private static CloseableHttpClient httpclient = HttpClients.createDefault();
    private static final String CHARSET = "UTF-8";

    public static CloseableHttpResponse httpPost(String url, String jsonArg, Map<String, String> header) {
        HttpPost httppost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(ConfigCenter.CONNECT_TIME_OUT).setConnectionRequestTimeout(ConfigCenter.CONNECT_REQUEST_TIME_OUT)
                .setSocketTimeout(ConfigCenter.SOCKET_TIME_OUT).build();
        httppost.setConfig(requestConfig);

        HttpEntity httpEntity = new StringEntity(jsonArg, CHARSET);
        httppost.setEntity(httpEntity);
        if (header != null) {
            for (Map.Entry<String, String> entry : header.entrySet()) {
                httppost.setHeader(entry.getKey(), entry.getValue());
            }
        }
        httppost.setHeader("Content-Type", "application/json");
        log.info("request url:{},request headers:{},request body:{}", url, Lists.newArrayList(httppost.getAllHeaders()).toString(), jsonArg);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httppost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                return response;
            } else {
                if (null != response) {
                    response.close();
                }
                log.warn("request failed,url:{},arg:{},return:{}", url, jsonArg, response.getStatusLine().toString());
            }
        } catch (IOException e) {
//            e.printStackTrace();
            log.warn("response stream exception,{}", e.toString());
            if (null != response) {
                try {
                    response.close();
                } catch (IOException e1) {
//                    e1.printStackTrace();
                    log.error("when response exception close response exception,{}", e1.toString());
                }
            }
        }
        return null;
    }
posted @ 2020-10-23 12:54  三毛是学IT掉发的  阅读(236)  评论(0编辑  收藏  举报