HttpClient封装成常规请求方法 get post 支持key-value和json 格式传参

/**
 * @Description Http|Https 请求工具类
 * @Author blake
 * @Date 2018/12/12 下午4:33
 * @Version 1.0
 */
public class HttpUtils {

    private static PoolingHttpClientConnectionManager connMgr;
    private static RequestConfig requestConfig;
    private static final int MAX_TIMEOUT = 7000;

    static {

        // 设置连接池
        connMgr = new PoolingHttpClientConnectionManager();

        // 设置连接池大小
        connMgr.setMaxTotal(100);
        connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());

        RequestConfig.Builder configBuilder = RequestConfig.custom();

        // 设置连接超时
        configBuilder.setConnectTimeout(MAX_TIMEOUT);

        // 设置读取超时
        configBuilder.setSocketTimeout(MAX_TIMEOUT);

        // 设置从连接池获取连接实例的超时
        configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);

        // 在提交请求之前 测试连接是否可用
        connMgr.setValidateAfterInactivity(5000);
        // configBuilder.setStaleConnectionCh
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是使用HttpClient5发送POST和GET请求Java代码示例: ```java import org.apache.hc.client5.http.classic.methods.HttpGet; import org.apache.hc.client5.http.classic.methods.HttpPost; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.HttpClients; import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.http.io.entity.StringEntity; import java.io.IOException; import java.net.URI; public class HttpClientUtils { /** * 发送GET请求 * * @param url 请求的URL * @return 响应字符串 * @throws IOException */ public static String sendGetRequest(String url) throws IOException { try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpGet httpGet = new HttpGet(url); ClassicHttpResponse response = httpClient.execute(httpGet); return response.getEntity().toString(); } } /** * 发送POST请求 * * @param url 请求的URL * @param params 请求参数(JSON格式) * @return 响应字符串 * @throws IOException */ public static String sendPostRequest(String url, String params) throws IOException { try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPost httpPost = new HttpPost(URI.create(url)); StringEntity requestEntity = new StringEntity(params, ContentType.APPLICATION_JSON); httpPost.setEntity(requestEntity); ClassicHttpResponse response = httpClient.execute(httpPost); return response.getEntity().toString(); } } } ``` 这里我们使用了Apache HttpClient5库来发送请求,通过封装方法,可以方便地在其他地方调用。注意,在使用完CloseableHttpClient后,一定要关闭它,否则可能会导致连接泄露和资源浪费。在上面的示例中,我们使用了try-with-resources语法糖来自动关闭CloseableHttpClient

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值