1. 程式人生 > 實用技巧 >http傳送url請求

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