httpclient 单例封装

本文介绍了如何使用 Java 的 HttpClient 进行单例封装,以提高网络请求的效率和资源利用率。通过创建一个静态内部类实现线程安全的单例,同时展示了如何配置 HttpClient 实例,包括设置超时时间、连接池等关键参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
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.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;


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

    private CloseableHttpClient httpclient;

    private RequestConfig requestConfig;

    private static SingletonHttpClient singleton;

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

        if (null == singleton) {
            synchronized (SingletonHttpClient.class) {
                if (null == singleton) {
                    singleton = new SingletonHttpClient();
                    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
                    cm.setMaxTotal(1000);
                    singleton.httpclient = HttpClients.custom().setConnectionManager(cm)
                            .disableAutomaticRetries().build();
                    singleton.requestConfig = RequestConfig.custom()
                            .setConnectionRequestTimeout(10000).setSocketTimeout(10000)
                            .setConnectTimeout(10000).build();
                    return singleton;
                } else {
                    return singleton;
                }
            }
        } else {
            return singleton;
        }
    }

    /**
     * POST 表单请求
     * @param url
     * @param headers
     * @param params
     * @return
     */
    public CloseableHttpResponse post(String url, Map<String, String> headers,
                                      Map<String, String> params) {

        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(this.requestConfig);

        if (null != headers) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpPost.addHeader(entry.getKey(), entry.getValue());
            }
        }

        List<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }

        try {
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(pairs);
            httpPost.setEntity(urlEncodedFormEntity);
            CloseableHttpResponse response = httpclient.execute(httpPost);
            return response;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            httpPost.releaseConnection();
        }
    }

    /**
     * POST 请求体请求
     * @param url
     * @param headers
     * @param body
     * @return
     */
    public CloseableHttpResponse post(String url, Map<String, String> headers, String body) {

        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(this.requestConfig);

        if (null != headers) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpPost.addHeader(entry.getKey(), entry.getValue());
            }
        }

        try {
            httpPost.setEntity(new StringEntity(body, "UTF-8"));
            CloseableHttpResponse response = httpclient.execute(httpPost);
            return response;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            httpPost.releaseConnection();
        }
    }

    /**
     * POST 单文件流(表单参数)
     * @param url
     * @param headers
     * @param name
     * @param in
     * @param contentType
     * @param fileName
     * @return
     */
    public String postFileStream(String url, Map<String, String> headers, Map<String, String> params,
                                 String name, InputStream in, ContentType contentType, String fileName) {

        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(this.requestConfig);

        if (null != headers) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpPost.addHeader(entry.getKey(), entry.getValue());
            }
        }

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        // 解决文件名中文乱码
        builder.setCharset(Charset.forName("utf-8"));
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

        for (Map.Entry<String, String> entry : params.entrySet()) {
            builder.addTextBody(entry.getKey(), entry.getValue());
        }

        builder.addBinaryBody(name, in, contentType, fileName);    
        InputStream dataInstreams = null;
        CloseableHttpResponse response = null;
        try {
            httpPost.setEntity(builder.build());
            response = httpclient.execute(httpPost);
            int dataStatus = -1;
            if(response!=null&&response.getStatusLine()!=null)
                dataStatus = response.getStatusLine().getStatusCode();

            HttpEntity dataEntity = response.getEntity();
            dataInstreams = dataEntity.getContent();
            String resp = IOUtils.toString(dataInstreams, "UTF-8");
            if(dataStatus==200){
                return resp;
            }else {
                throw new RuntimeException("获取数据失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                in.close(); // 关闭流
                httpPost.releaseConnection();
            } catch (IOException e) {
                e.printStackTrace();
            }    
        }
    }

    /**
     * POST 单文件流
     * @param url
     * @param headers
     * @param in
     * @return
     */
    public String postFileStream(String url, Map<String, String> headers,
                                 InputStream in) {

        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(this.requestConfig);

        if (null != headers) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpPost.addHeader(entry.getKey(), entry.getValue());
            }
        }
        InputStream dataInstreams = null;
        CloseableHttpResponse response = null;
        try {
            httpPost.setEntity(new InputStreamEntity(in));
            response = httpclient.execute(httpPost);
            int dataStatus = -1;
            if(response!=null&&response.getStatusLine()!=null)
                dataStatus = response.getStatusLine().getStatusCode();

            HttpEntity dataEntity = response.getEntity();
            dataInstreams = dataEntity.getContent();
            String resp = IOUtils.toString(dataInstreams, "UTF-8");
            if(dataStatus==200){
                return resp;
            }else {
                throw new RuntimeException("获取数据失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                in.close(); // 关闭流
                httpPost.releaseConnection();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * POST json数据
     * @param url
     * @param headers
     * @param jsonObject
     * @return
     */
    public String postjson(String url, Map<String, String> headers, JSONObject jsonObject) {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(this.requestConfig);

        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);

        InputStream dataInstreams = null;
        CloseableHttpResponse response = null;
        try {
//            System.out.println("header="+JSONObject.fromObject(headers));
            response = httpclient.execute(httpPost);
            int dataStatus = -1;
            if(response!=null&&response.getStatusLine()!=null)
                dataStatus = response.getStatusLine().getStatusCode();

            HttpEntity dataEntity = response.getEntity();
            dataInstreams = dataEntity.getContent();
            String resp = IOUtils.toString(dataInstreams, "UTF-8");

            System.out.println("resp="+resp);
            if(dataStatus==200){
                return resp;
            }else {
                throw new RuntimeException("调用机考接口失败,不能获得机考信息");
            }
        }catch (IOException e) {
//            throw new HvnRuntimeException(e);
            return null;
        }finally {
           IOUtils.closeQuietly(dataInstreams);
            IOUtils.closeQuietly(response);
            httpPost.releaseConnection();
        }
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值