Java封装httpclient的get和post请求

该代码段展示了如何在Java中使用ApacheHttpClient库封装HTTP的GET和POST请求。通过静态初始化创建了一个连接池管理器和HttpClient实例,并设置了超时配置。doGet和doPost方法分别处理GET和POST请求,接受URL和参数Map,返回响应数据。
摘要由CSDN通过智能技术生成

Java封装httpclient的get和post请求


直接上代码,复制粘贴后,需要导入依赖则导入对应依赖,传入url地址和map类型的参数直接调用公共方法即可。

package com.yonyoufutong.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
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.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Map;

@Slf4j
public class RequestTools {

    private static final String HEADER_CONTENT_JSON = "application/json";

    private static final String DEFAULT_CHARSET = "UTF-8";

    private static PoolingHttpClientConnectionManager cm = null;

    private static CloseableHttpClient httpClient;

    private static boolean islog = false;

    static {
        cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(500);
        cm.setDefaultMaxPerRoute(50);

        RequestConfig globalConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(5000)         // 连接池获取连接超时
                .setConnectTimeout(5000)                   // 连接建立超时
                .setSocketTimeout(20000)                    // 等待响应超时
                .setCookieSpec(CookieSpecs.IGNORE_COOKIES)
                .build();

        httpClient = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(globalConfig).build();
    }

    private static CloseableHttpClient getHttpClient() {
        return httpClient;
    }

  

    /**
     * @param requestUrl
     * @param paramMap
     * @return
     * @throws IOException
     */
    public static String doGet(String requestUrl, Map<String, Object> paramMap) throws IOException {
        CloseableHttpClient httpClient = getHttpClient();
        StringBuilder param = new StringBuilder("?");
        if (paramMap != null) {
            for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
                param.append(entry.getKey());
                param.append("=");
                param.append(entry.getValue());
                param.append("&");
            }
            param.deleteCharAt(param.length() - 1);
        }
        if (islog) {
            System.out.println("这是请求参数:" + param);
        }
        String url = requestUrl + param;
        HttpGet get = new HttpGet(url);
        String responseString = httpClient.execute(get, response -> EntityUtils.toString(response.getEntity()));
        if (islog) {
            System.out.println("这是返回数据:" + responseString);
        }
        get.releaseConnection();
        return responseString;
    }

    public static String doPost(String requestUrl, Object param) throws IOException {
        CloseableHttpClient httpClient = getHttpClient();
        HttpPost post = new HttpPost(requestUrl);
        post.setHeader("Content-Type", "application/json;charset=UTF-8");
        ObjectMapper mapper = new ObjectMapper();
        String requestParam = mapper.writeValueAsString(param);
        if (islog) {
            System.out.println("这是请求参数:" + requestParam);
        }
        // log.error("请求参数:" + requestParam);
        post.setEntity(new StringEntity(requestParam, "text/plain", "UTF-8"));
        String responseString = httpClient.execute(post, response -> EntityUtils.toString(response.getEntity()));
        if (islog) {
            System.out.println("这是返回数据:" + responseString);
        }
        // log.error("返回参数:" + responseString);
        return responseString;
    }


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值