栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JAVA常用http请求工具类封装

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JAVA常用http请求工具类封装

几乎每个web项目都会用到http请求,空闲时间封装了一个工具类,分享出来,用到的时候可以直接拷贝使用

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NamevaluePair;
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.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNamevaluePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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


public class HttpUtil {
    private static Logger log = LoggerFactory.getLogger(HttpUtil.class);
    private static PoolingHttpClientConnectionManager connectionManager = null;
    private static HttpClientBuilder httpBuilder = null;
    private static RequestConfig requestConfig = null;

    
    private static int MAX_ConNECTION = 100;
    
    private static int DEFAULT_MAX_ConNECTION = 50;

    static {
        //设置http的状态参数
        requestConfig = RequestConfig.custom()
                .setSocketTimeout(10000)
                .setConnectTimeout(10000)
                .setConnectionRequestTimeout(10000)
                .build();

        connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(MAX_CONNECTION);
        connectionManager.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTION);
        httpBuilder = HttpClients.custom();
        httpBuilder.setConnectionManager(connectionManager);
    }

    
    public static CloseableHttpClient getConnection() {
        return httpBuilder.build();
    }

    
    public static String httpPost(String url, Map paramsMap) throws Exception {
        List params = new ArrayList<>();

        for (Map.Entry e : paramsMap.entrySet()) {
            NamevaluePair pair = new BasicNamevaluePair(e.getKey(), e.getValue());
            params.add(pair);
        }

        HttpUriRequest postMethod = RequestBuilder.post().setUri(url)
                .addParameters(params.toArray(new BasicNamevaluePair[params.size()]))
                .setConfig(requestConfig).build();

        HttpResponse response = getConnection().execute(postMethod);

        return EntityUtils.toString(response.getEntity());
    }

    
    public static String httpPostJson(String url, String jsonStr) throws Exception {

        HttpUriRequest postMethod = RequestBuilder.post().setUri(url)
                .setHeader("Content-Type", "application/json;charset=utf-8")
                .setHeader("Accept", "application/json")
                .setEntity(new StringEntity(jsonStr, Charset.forName("UTF-8")))
                .setConfig(requestConfig).build();
        HttpResponse response = getConnection().execute(postMethod);

        return EntityUtils.toString(response.getEntity());
    }

    
    public static String httpGet(String url) throws Exception {
        HttpUriRequest getMethod = RequestBuilder.get().setUri(url)
                .setConfig(requestConfig).build();

        HttpResponse response = getConnection().execute(getMethod);

        return EntityUtils.toString(response.getEntity());
    }

    
    public static String httpGet(String url, Map paramsMap) throws Exception {
        List params = new ArrayList<>();

        for (Map.Entry e : paramsMap.entrySet()) {
            NamevaluePair pair = new BasicNamevaluePair(e.getKey(), e.getValue());
            params.add(pair);
        }

        HttpUriRequest getMethod = RequestBuilder.get().setUri(url)
                .addParameters(params.toArray(new BasicNamevaluePair[params.size()]))
                .setConfig(requestConfig).build();

        HttpResponse response = getConnection().execute(getMethod);

        return EntityUtils.toString(response.getEntity());
    }

    
    public static String httpPostNoPool(String url, Map params) {
        CloseableHttpClient closeableHttpClient = null;
        try {
            HttpPost httpPost = new HttpPost(url);

            if (params != null) {
                List form = new ArrayList<>();

                for (String name : params.keySet()) {
                    form.add(new BasicNamevaluePair(name, params.get(name)));
                }

                httpPost.setEntity(new UrlEncodedFormEntity(form, HTTP.UTF_8));
            }

            closeableHttpClient = HttpClients.createDefault();
            CloseableHttpResponse httpResponse = closeableHttpClient.execute(httpPost);
            HttpEntity entry = httpResponse.getEntity();
            return EntityUtils.toString(entry);
        } catch (Exception e) {
            log.error("HttpUtil.httpPost failed!", e);
        } finally {
            if (null != closeableHttpClient) {
                try {
                    closeableHttpClient.close();
                } catch (IOException e) {
                    log.error("closeableHttpClient.close failed!", e);
                }
            }
        }

        return null;
    }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/644577.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号