天天看点

HttpUtils(POST/GET)

1.maven依赖

<dependency>
    <groupId>commons-collections</groupId>
    <artifactId>commons-collections</artifactId>
    <version>3.2.2</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.2</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
    <version>4.4</version>
</dependency>
           

2.HttpUtils(POST/GET)

public final class HttpUtils {
    private HttpUtils() {}

    /**
     * contentType: application/json
     */
    public static String post(String address, Map<String, String> headers, String body) {
        StringBuilder sb = new StringBuilder();
        try {
            CloseableHttpClient httpclient = HttpClientBuilder.create().build();
            HttpPost httpPost = new HttpPost(address);
            if (StringUtils.isNotBlank(body)) {
                StringEntity stringEntity = new StringEntity(body);
                stringEntity.setContentEncoding("UTF-8");
                stringEntity.setContentType("application/json");
                httpPost.setEntity(stringEntity);
            }
            if (MapUtils.isNotEmpty(headers)) {
                setHeaders(httpPost, headers);
            }
            HttpResponse response = httpclient.execute(httpPost);
            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                sb.append(EntityUtils.toString(response.getEntity()));
            }
            httpPost.releaseConnection();
        } catch (Exception e) {
            throw new RuntimeException("网络请求失败");
        }
        return sb.toString();
    }

    /**
     * contentType: key/value
     */
    public static String post(String address, Map<String, String> headers,  Map<String, String> paramsMap) {
        StringBuilder sb = new StringBuilder();
        try {
            CloseableHttpClient httpclient = HttpClientBuilder.create().build();
            HttpPost httpPost = new HttpPost(StringUtils.trim(address));
            if (MapUtils.isNotEmpty(paramsMap)) {
                List<NameValuePair> params = getParams(paramsMap);
                httpPost.setEntity(new UrlEncodedFormEntity(params));
            }
            if (MapUtils.isNotEmpty(headers)) {
                setHeaders(httpPost, headers);
            }
            CloseableHttpResponse response = httpclient.execute(httpPost);
            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                sb.append(EntityUtils.toString(response.getEntity(), "utf-8"));
            }
            httpPost.releaseConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    /**
     * GET (INCLUDE HEADERS)
     */
    public static String get(String address, Map<String, String> headers) {
        StringBuilder sb = new StringBuilder();
        try {
            CloseableHttpClient httpclient = HttpClientBuilder.create().build();
            HttpGet httpGet = new HttpGet(StringUtils.trim(address));
            if (MapUtils.isNotEmpty(headers)) {
                setHeaders(httpGet, headers);
            }
            CloseableHttpResponse response = httpclient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                sb.append(EntityUtils.toString(response.getEntity(), "utf-8"));
            }
            httpGet.releaseConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    private static void setHeaders(HttpRequestBase request, Map<String, String> headers) {
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            request.setHeader(entry.getKey(), entry.getValue());
        }
    }

    private static List<NameValuePair> getParams(Map<String, String> paramsMap) {
        List<NameValuePair> params = new ArrayList<>();
        for (String key : paramsMap.keySet()) {
            params.add(new BasicNameValuePair(key, paramsMap.get(key)));
        }
        return params;
    }
}
           

继续阅读