HttpUtils方法整理|代码通过http请求数据(get,set)

该博客主要介绍了一个用于执行HTTPS GET和POST请求的Java工具类。类中包含了初始化HTTP客户端、设置超时时间、忽略证书验证等功能,确保了与服务器的安全通信。同时,提供了发送带参数GET和POST请求的方法,以及处理响应结果的辅助方法。

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

package com.hundsun.front.utils;

import java.io.IOException;
import java.nio.charset.CodingErrorAction;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.config.ConnectionConfig;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
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.client.LaxRedirectStrategy;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hundsun.ftenant.common.exception.TengException;

/**
 * 
 * 
 * 项目名称:net.hs.itn.stockwin.game.impl 类名称:HttpMarketDemoUtils 类描述: openAPI行情 请求 工具类 创建人:qish12799 创建时间:2015年9月24日 下午8:21:07
 * 
 * @version
 * 
 */
public class HttpUtils {

    private static Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * HTTP HEADER字段 Authorization应填充字符串Bearer
     */
    public static final String BEARER = "Bearer ";

    private static CloseableHttpClient httpClient = null;
    /** 连接超时时间 */
    public final static int CONNECT_TIMEOUT = 15000;

    /** socket连接超时时间 */
    public final static int SOCKET_TIMEOUT = 20000;

    /** 发送请求相应时间 */
    public final static int REQUEST_TIMEOUT = 15000;
    /**
     * 传输超时时间
     */
    private static final int SO_TIMEOUT = 60 * 1000;
    public static final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    /**
     * 最大连接数
     */
    public final static int MAX_TOTAL_CONNECTIONS = 500;
    /**
     * 每个路由最大连接数 访问每个目标机器 算一个路由 默认 2个
     */
    public final static int MAX_ROUTE_CONNECTIONS = 80;

    /**
     * 编码格式:utf-8
     */
    private static final String CHARSET_UTF_8 = "UTF-8";

    static {
        cm.setDefaultMaxPerRoute(MAX_ROUTE_CONNECTIONS);// 设置最大路由数
        cm.setMaxTotal(MAX_TOTAL_CONNECTIONS);// 最大连接数
        SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build();
        cm.setDefaultSocketConfig(socketConfig);
        RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH).setExpectContinueEnabled(true).setStaleConnectionCheckEnabled(true).setRedirectsEnabled(true).build();
        ConnectionConfig connectionConfig = ConnectionConfig.custom().setCharset(Consts.UTF_8).setMalformedInputAction(CodingErrorAction.IGNORE).setUnmappableInputAction(CodingErrorAction.IGNORE).build();
        httpClient = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(defaultRequestConfig).setDefaultConnectionConfig(connectionConfig).build();
    }

    /**
     * https请求get
     * 
     * @param url
     * @return
     * @throws IOException
     * @throws Exception
     */
    public static String doGet(String url) throws TengException, IOException {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse resp = null;
        String rtnValue = null;
        try {
            httpClient = HttpUtils.getHttpsClient();
            HttpGet httpGet = new HttpGet(url);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SO_TIMEOUT).setConnectTimeout(CONNECT_TIMEOUT).build();// 设置请求和传输超时时间
            httpGet.setConfig(requestConfig);
            resp = httpClient.execute(httpGet);
            rtnValue = EntityUtils.toString(resp.getEntity(), CHARSET_UTF_8);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new TengException("Exception", e.getMessage());
        } finally {
            if (null != resp) {
                resp.close();
            }
            if (null != httpClient) {
                httpClient.close();
            }
        }
        return rtnValue;
    }

    public static String sendPost(String url, Map<String, String> params, HttpHost proxy, String authorization) {
        try {
            HttpPost post = new HttpPost(url);
            Builder builder = RequestConfig.custom();
            if (proxy != null) {
                builder.setProxy(proxy);
                RequestConfig requestConfig = builder.setSocketTimeout(SOCKET_TIMEOUT).setConnectTimeout(CONNECT_TIMEOUT).setConnectionRequestTimeout(REQUEST_TIMEOUT).setExpectContinueEnabled(false).setRedirectsEnabled(true).build();
                post.setConfig(requestConfig);
            }

            post.setHeader("Content-Type", "application/x-www-form-urlencoded");
            post.setHeader("Authorization", authorization);
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            StringBuffer sb = new StringBuffer();
            if (params != null) {
                int n = 0;
                for (Entry<String, String> set : params.entrySet()) {
                    if (n == 0) {
                        n++;
                        sb.append(set.getKey() + "=" + set.getValue());
                    } else {
                        sb.append("&" + set.getKey() + "=" + set.getValue());
                    }
                    nvps.add(new BasicNameValuePair(set.getKey(), set.getValue()));
                }
            }
            post.setEntity(new UrlEncodedFormEntity(nvps, CHARSET_UTF_8));

            HttpResponse response = httpClient.execute(post);
            int status = response.getStatusLine().getStatusCode();

            String result = getResultFromResponse(response, status);
            if (status == 200) {
                return result;
            }

        } catch (ClientProtocolException e) {
            logger.error("HttpClient   请求  ClientProtocolException ", e, logger);
        } catch (IOException e) {
            logger.error("HttpClient   请求  IOException ", e, logger);
        }
        return null;
    }

    /**
     * @param response
     * @return
     */
    private static String getResultFromResponse(HttpResponse response, int status) {
        HttpEntity entity = null;
        String result = null;
        try {
            entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity, CHARSET_UTF_8);
                logger.error("HttpClient   请求 http状态码 status = [" + status + "]  请求结果  : " + result);
            }

        } catch (Exception e) {
            logger.error("HttpClient   请求 http状态码 status = [" + status + "]  获取HttpEntity ", e, logger);
        } finally {
            if (entity != null) {
                try {
                    entity.getContent().close();
                } catch (IllegalStateException | IOException e) {
                    logger.error("close entity error", e, logger);
                }
            }
        }
        return result;
    }

    /**
     * get请求
     * 
     * @param url
     * @param params
     * @param charSet
     * @return
     */
    public static String sendGet(String url, Map<String, String> params, String charSet, HttpHost proxy, String authorization, String interfacename) {
        logger.info("send get interface name :" + interfacename);
        try {
            StringBuffer urlbuf = getUrlBuf(url, params);
            //            StringBuffer urlbuf = new StringBuffer(url);
            //            if (params != null) {
            //                int n = 0;
            //                for (Entry<String, String> set : params.entrySet()) {
            //                    if (!urlbuf.toString().contains("?")) {
            //                        urlbuf.append("?");
            //                    }
            //                    if (n != 0) {
            //                        urlbuf.append("&");
            //                    }
            //                    urlbuf.append(set.getKey()).append("=").append(set.getValue());
            //                    n++;
            //                }
            //            }
            logger.debug("get = " + urlbuf.toString(), logger);
            HttpGet get = new HttpGet(urlbuf.toString());
            get.setHeader("Content-Type", "application/x-www-form-urlencoded");
            get.setHeader("Authorization", authorization);
            Builder builder = RequestConfig.custom();
            if (proxy != null) {
                builder.setProxy(proxy);
            }

            RequestConfig defaultConfig = builder.setSocketTimeout(SOCKET_TIMEOUT).setConnectTimeout(CONNECT_TIMEOUT).setConnectionRequestTimeout(REQUEST_TIMEOUT).setExpectContinueEnabled(false).setRedirectsEnabled(true).build();
            get.setConfig(defaultConfig);

            HttpResponse response = httpClient.execute(get);

            int status = response.getStatusLine().getStatusCode();
            return getResultFromResponse(response, status, charSet);
            //            HttpEntity entity = null;
            //            try {
            //                entity = response.getEntity();
            //                if (entity != null) {
            //                    String result = EntityUtils.toString(entity, charSet);
            //                    return result;
            //                }
            //            } catch (Exception e) {
            //                logger.error("HttpClient   请求 http状态码 status = [" + status + "]  ", e, logger);
            //            } finally {
            //                if (entity != null) {
            //                    entity.getContent().close();
            //                }
            //            }
        } catch (ClientProtocolException e) {
            logger.error("HttpClient   请求  ClientProtocolException ", e, logger);
        } catch (IOException e) {
            logger.error("HttpClient   请求  IOException ", e, logger);
        }
        return null;
    }

    /**
     * @param url
     * @param params
     * @return
     */
    private static StringBuffer getUrlBuf(String url, Map<String, String> params) {
        StringBuffer urlbuf = new StringBuffer(url);
        if (params != null) {
            int n = 0;
            for (Entry<String, String> set : params.entrySet()) {
                if (!urlbuf.toString().contains("?")) {
                    urlbuf.append("?");
                }
                if (n != 0) {
                    urlbuf.append("&");
                }
                urlbuf.append(set.getKey()).append("=").append(set.getValue());
                n++;
            }
        }
        return urlbuf;
    }

    /**
     * @param response
     * @param status
     * @return
     */
    private static String getResultFromResponse(HttpResponse response, int status, String charSet) {
        HttpEntity entity = null;
        String result = null;
        try {
            entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity, charSet);

            }
        } catch (Exception e) {
            logger.error("HttpClient   请求 http状态码 status = [" + status + "]  ", e, logger);
        } finally {
            if (entity != null) {
                try {
                    entity.getContent().close();
                } catch (IllegalStateException | IOException e) {
                    logger.error("close entity error", e, logger);
                }
            }
        }
        return result;
    }

    /**
     * https请求get
     * 
     * @param url
     * @return
     * @throws Exception
     */
    public static String sendHttpsGet(String url) throws Exception {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse resp = null;
        String rtnValue = null;
        try {
            httpClient = HttpUtils.getHttpsClient();
            HttpGet httpGet = new HttpGet(url);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SOCKET_TIMEOUT).setConnectTimeout(CONNECT_TIMEOUT).build();// 设置请求和传输超时时间
            httpGet.setConfig(requestConfig);
            resp = httpClient.execute(httpGet);
            rtnValue = EntityUtils.toString(resp.getEntity(), CHARSET_UTF_8);
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        } finally {
            if (null != resp) {
                resp.close();
            }
            if (null != httpClient) {
                httpClient.close();
            }
        }
        return rtnValue;
    }

    /**
     *
     * @param url
     * @param paraMap
     * @return
     * @throws Exception
     */
    public static String sendHttpsPost(String url, Map<String, Object> paraMap) throws Exception {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse resp = null;
        String rtnValue = null;
        try {
            // 获取https安全客户端
            httpClient = HttpUtils.getHttpsClient();
            HttpPost httpPost = new HttpPost(url);
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            if (null != paraMap && paraMap.size() > 0) {
                for (Entry<String, Object> entry : paraMap.entrySet()) {
                    list.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
                }
            }

            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SOCKET_TIMEOUT).setConnectTimeout(CONNECT_TIMEOUT).build();// 设置请求和传输超时时间
            httpPost.setConfig(requestConfig);
            httpPost.setEntity(new UrlEncodedFormEntity(list, CHARSET_UTF_8));
            resp = httpClient.execute(httpPost);
            rtnValue = EntityUtils.toString(resp.getEntity(), CHARSET_UTF_8);

        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        } finally {
            if (null != resp) {
                resp.close();
            }
            if (null != httpClient) {
                httpClient.close();
            }
        }

        return rtnValue;
    }

    /**
     * 获取https,单向验证
     * 
     * @return
     * @throws Exception
     */
    public static CloseableHttpClient getHttpsClient() {
        try {
            TrustManager[] trustManagers = new TrustManager[] { new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException {
                    // Do nothing because of X and Y.
                }

                @Override
                public void checkServerTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException {
                    // Do nothing because of X and Y.
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    //                    return null;
                    return new X509Certificate[0];
                }
            } };
            SSLContext sslContext = SSLContext.getInstance(SSLConnectionSocketFactory.TLS);
            sslContext.init(new KeyManager[0], trustManagers, new SecureRandom());
            SSLContext.setDefault(sslContext);
            sslContext.init(null, trustManagers, null);
            SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            HttpClientBuilder clientBuilder = HttpClients.custom().setSSLSocketFactory(connectionSocketFactory);
            clientBuilder.setRedirectStrategy(new LaxRedirectStrategy());
            CloseableHttpClient httpClient = clientBuilder.build();
            return httpClient;
        } catch (Exception e) {
            logger.error("http client 远程连接失败", e);
            throw new TengException("http client 远程连接失败", e.toString());
        }
    }


    /**
     * sendHttpsGetAddTocken
     * @param url
     * @param tockenName
     * @param tockenValue
     * @return
     * @throws Exception
     * by lipeng
     */
    public static String sendHttpsGetAddTocken(String url, String tockenName, String tockenValue) throws Exception {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse resp = null;
        String rtnValue = null;
        try {
            httpClient = HttpUtils.getHttpsClient();
            HttpGet httpGet = new HttpGet(url);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SOCKET_TIMEOUT).setConnectTimeout(CONNECT_TIMEOUT).build();// 设置请求和传输超时时间
            httpGet.setConfig(requestConfig);
            httpGet.setHeader(tockenName,tockenValue);
            resp = httpClient.execute(httpGet);
            rtnValue = EntityUtils.toString(resp.getEntity(), CHARSET_UTF_8);
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        } finally {
            if (null != resp) {
                resp.close();
            }
            if (null != httpClient) {
                httpClient.close();
            }
        }
        return rtnValue;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值