美文网首页
httpclient框架实现http的调用

httpclient框架实现http的调用

作者: 天草二十六_简村人 | 来源:发表于2023-02-19 16:53 被阅读0次

一、pom.xml

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.10</version>
        </dependency>

二、HttpUtils

import com.google.common.base.Charsets;
import org.apache.http.HttpHeaders;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

import static org.apache.http.client.utils.HttpClientUtils.closeQuietly;

public class HttpUtils {

    private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    private static CloseableHttpClient httpClient = HttpClients.custom()
//设置socket进行3次握手建立连接的超时时间
.setConnectTimeout(1000)
//设置连接超时时间,即socket读写超时时间
.setSocketTimeout(5000)
//设置individual route连接池中最大的连接数,默认为2
.setMaxConnPerRoute(256)
//设置global连接池中最大的连接数,默认为20
.setMaxConnTotal(256)
.disableContentCompression()
.disableAutomaticRetries()
.build();

    /**
     * 发送get请求
     *
     * @param url
     * @return
     */
    public static String get(String url) throws IOException {
        CloseableHttpResponse response = null;

        try {
            HttpGet httpGet = new HttpGet(url);
            response = httpClient.execute(httpGet);
            return readResponseString(response);
        } catch (Exception e) {
            throw e;
        } finally {
            closeQuietly(response);
        }
    }

    /**
     * 发送post请求
     *
     * @param url
     * @param body
     * @return
     */
    public static String post(String url, String body) throws IOException {
        CloseableHttpResponse response = null;

        try {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
            StringEntity entity = new StringEntity(body, Charsets.UTF_8.name());
            entity.setContentEncoding(Charsets.UTF_8.name());
            httpPost.setEntity(entity);
            response = httpClient.execute(httpPost);
            return readResponseString(response);
        } catch (Exception e) {
            throw e;
        } finally {
            closeQuietly(response);
        }
    }

    private static String readResponseString(CloseableHttpResponse response) throws IOException {
        int status = response.getStatusLine().getStatusCode();

        if (status / 100 == 2) {
            return EntityUtils.toString(response.getEntity());
        } else {
            throw new HttpResponseException(status, EntityUtils.toString(response.getEntity()));
        }
    }
}

相关文章

网友评论

      本文标题:httpclient框架实现http的调用

      本文链接:https://www.haomeiwen.com/subject/genikdtx.html