httpClient工具的单例封装

 httpClient客户端采用单例设计模式,CloseableHttpClient也是单例。

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;
import java.util.Set;


import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.config.RequestConfig;
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.client.utils.URIBuilder;
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.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;


/**
 * http client 单例封装
 */
public class SingletonHttpClient {

    private static CloseableHttpClient httpclient;

    private static RequestConfig requestConfig;

    private static SingletonHttpClient singletonHttpClient = new SingletonHttpClient();

    private SingletonHttpClient(){}

    static{
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(1000);
        httpclient = HttpClients.custom().setConnectionManager(cm)
                .disableAutomaticRetries().build();
        requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(10000).setSocketTimeout(10000)
                .setConnectTimeout(10000).build();
    }

    /**
     * 获取实例,并初始化
     */
    public static SingletonHttpClient getInstance() {
        return singletonHttpClient;
    }

    /**
     * get 请求
     * @param url 请求地址
     * @param headers 请求头
     * @param param 请求参数
     * @return 请求响应
     */
    public String doGet(String url, Map<String, String> headers, Map<String, String> param) {
        CloseableHttpResponse response;
        try {
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                Set<Map.Entry<String, String>> entries = param.entrySet();
                for (Map.Entry<String, String> entry : entries) {
                    builder.addParameter(entry.getKey(), entry.getValue());
                }
            }
            URI uri = builder.build();
            HttpGet httpGet = new HttpGet(uri);
            httpGet.setConfig(requestConfig);
            if(headers != null) {
	            for (Map.Entry<String, String> entry : headers.entrySet()) {
		            httpGet.addHeader(entry.getKey(), entry.getValue());
	            }
            }
            response = httpclient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (URISyntaxException | IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * POST 请求
     * @param url 请求地址
     * @param headers 请求头
     * @param jsonObject 请求体
     * @return 请求响应
     */
    public String doPostJson(String url, Map<String, String> headers, JSONObject jsonObject) {
        CloseableHttpResponse response;
        try {
            HttpPost httpPost = new HttpPost(new URIBuilder(url).build());
            httpPost.setConfig(requestConfig);
            if(headers != null) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    httpPost.addHeader(entry.getKey(), entry.getValue());
                }
            }
            httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
            StringEntity stringEntity = new StringEntity(jsonObject.toString(), "utf-8");
            stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            httpPost.setEntity(stringEntity);
            response = httpclient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (URISyntaxException | IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值