標準Http請求工具類,拿去就用,別整那些花裏胡哨的

/**
 * @Author wangxy
 * @Date 2019/6/17 17:20
 * @Description http請求工具類
 **/
@Slf4j
public class HttpUtils {

    // 默認配置
    private static RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(6000)
            .setConnectionRequestTimeout(6000).setSocketTimeout(6000).build();

    public static String doGet(String url, Map<String, String> headers, boolean isHttps) {
        return http("get", url, null, headers, isHttps);
    }

    public static String doDelete(String url, Map<String, String> headers, boolean isHttps) {
        return http("delete", url, null, headers, isHttps);
    }

    public static String doPost(String url, String body, Map<String, String> headers, boolean isHttps) {
        return http("post", url, body, headers, isHttps);
    }

    public static String doPut(String url, String body, Map<String, String> headers, boolean isHttps) {
        return http("put", url, body, headers, isHttps);
    }

    private static String http(String method, String url, String body,
                               Map<String, String> headers, boolean isHttps) {
        long start = System.currentTimeMillis();
        try {
            if (log.isDebugEnabled()) {
                log.debug("請求入參:method = {},url = {},body = {},headers = {},isHttps = {}", method, url, body, headers, isHttps);
            }
            HttpClient httpClient;
            if (isHttps) {
                httpClient = createSSLClientDefault();
            } else {
                httpClient = HttpClients.createDefault();
            }
            url = restEncode(url);
            if ("post".equalsIgnoreCase(method)) {
                HttpPost post = new HttpPost(url);
                post.setConfig(requestConfig);
                if (!MapUtils.isEmpty(headers)) {
                    headers.forEach(post::setHeader);
                }
                post.setEntity(new StringEntity(body, ContentType.APPLICATION_JSON));
                HttpResponse response = httpClient.execute(post);
                return parseRes(response);
            } else if ("get".equalsIgnoreCase(method)) {
                HttpGet get = new HttpGet(url);
                get.setConfig(requestConfig);
                if (!MapUtils.isEmpty(headers)) {
                    headers.forEach(get::setHeader);
                }
                HttpResponse response = httpClient.execute(get);
                return parseRes(response);
            } else if ("delete".equalsIgnoreCase(method)) {
                HttpDelete delete = new HttpDelete(url);
                delete.setConfig(requestConfig);
                if (!MapUtils.isEmpty(headers)) {
                    headers.forEach(delete::setHeader);
                }
                HttpResponse response = httpClient.execute(delete);
                return parseRes(response);
            } else if ("put".equalsIgnoreCase(method)) {
                HttpPut put = new HttpPut(url);
                put.setConfig(requestConfig);
                if (!MapUtils.isEmpty(headers)) {
                    headers.forEach(put::setHeader);
                }
                put.setEntity(new StringEntity(body, ContentType.APPLICATION_JSON));
                HttpResponse response = httpClient.execute(put);
                return parseRes(response);
            } else {
                throw new IllegalArgumentException("Unsupported request method");
            }
        } catch (IOException e) {
            throw new RuntimeException(String.format("請求異常:url=[%s],error=[%s]", url, e.getMessage()));
        } finally {
            if (log.isDebugEnabled()) {
                log.info("請求耗時:{}", System.currentTimeMillis() - start + " ms");
            }
        }
    }

    /**
     * 解析響應結果
     *
     * @param response
     * @return
     * @throws IOException
     */
    private static String parseRes(HttpResponse response) throws IOException {
        return EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
    }

    /**
     * 創建https
     *
     * @return
     */
    private static CloseableHttpClient createSSLClientDefault() {
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(
                    null, (x509Certificates, s) -> true).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
            e.printStackTrace();
        }
        return HttpClients.createDefault();
    }

    private static String restEncode(String url) {
        return url.replaceAll(" ", "%20");
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章