java中使用Apache HttpClient发送Http请求,并获取返回结果

发送http请求可以写成一个工具类,HttpClient可以使用连接池创建,这样的好处是我们可以自己定义一些配置,比如请求超时时间,最大连接数等等。

public class HttpUtil {
    private static CloseableHttpClient httpClient;
    private static RequestConfig requestConfig = RequestConfig.custom()
            .setSocketTimeout(5000)
            .setConnectTimeout(5000)
            .setConnectionRequestTimeout(5000)
            .build();

    static {
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
        connManager.setMaxTotal(300);
        connManager.setDefaultMaxPerRoute(300);
        httpClient = HttpClients.custom().setConnectionManager(connManager).build();
    }

    // get请求
    public static String get(String url) throws IOException {
        HttpGet httpget = new HttpGet(url);
        httpget.setConfig(requestConfig);
        try (CloseableHttpResponse response = httpClient.execute(httpget)) {
            return EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
        }
    }

    // post请求
    public static String post(String url, String json) throws IOException {
        HttpEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(entity);
        httpPost.setConfig(requestConfig);
        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            return EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
        }
    }

如果url后面需要接参数,那么可以写个方法将参数拼在url后面即可。

你可能感兴趣的:(java基础)