httpclient请求公共类

package com.neusoft.snet.app.thirdpart.api.util;

import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.*;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.MalformedChallengeException;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description http工具类
 * @Author 
 */
@Data
@Slf4j
public class HttpUtil {

    /**
     * GET请求--无参
     */
    public static String doGet(String url, boolean proxy) {
        log.info("请求地址:{} , 是否开启代理{}", url, proxy);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //设置请求和传输超时时间
        //单位毫秒
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(3000).setConnectTimeout(3000)
                .setSocketTimeout(3000).build();//设置请求的状态参数
        try {
            HttpGet httpGet = new HttpGet(url);
            httpGet.setConfig(requestConfig);
            CloseableHttpResponse response = null;
            if (proxy) {
                response = httpClient.execute(httpGet, setProxy(httpGet));
            } else {
                response = httpClient.execute(httpGet);
            }
            return response(httpClient, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * GET请求--有参
     */
    public static String doGet(String url, Map<String, String> params, boolean proxy) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();
        try {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            if (params != null) {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
            }
            String paramsStr = EntityUtils.toString(new UrlEncodedFormEntity(nvps, "UTF-8"));
            url = url + "?" + paramsStr;
            HttpGet httpGet = new HttpGet(url);
            httpGet.setConfig(requestConfig);
            CloseableHttpResponse response = null;
            if (proxy) {
                response = httpClient.execute(httpGet, setProxy(httpGet));
            } else {
                response = httpClient.execute(httpGet);
            }
            return response(httpClient, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * GET请求--有参
     * 有请求头
     */
    public static String doGet(String url, JSONObject jsonObject, Map<String, String> params, boolean proxy) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();
        try {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            if (params != null) {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
            }
            String paramsStr = EntityUtils.toString(new UrlEncodedFormEntity(nvps, "UTF-8"));
            url = url + "?" + paramsStr;
            HttpGet httpGet = new HttpGet(url);
            for (String str : jsonObject.keySet()) {
                httpGet.setHeader(str, jsonObject.getString(str));
            }
            httpGet.setConfig(requestConfig);
            CloseableHttpResponse response = null;
            if (proxy) {
                response = httpClient.execute(httpGet, setProxy(httpGet));
            } else {
                response = httpClient.execute(httpGet);
            }
            return response(httpClient, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * POST请求
     */
    public static String doPost(String url, String params, boolean proxy) {
        try {
            log.info("请求地址:{} , 参数:{} , 是否开启代理:{}", url, params, proxy);
            HttpPost httpPost = new HttpPost(url);
            return getResponse(httpPost, params, proxy);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * POST请求
     *
     * @param url        请求地址
     * @param jsonObject header参数
     * @param params     body参数
     * @param proxy      代理开关
     * @return
     */
    public static String doPost(
            String url,
            JSONObject jsonObject,
            String params,
            boolean proxy
    ) {
        try {
            log.error("远程服务器!服务器地址{},请求头参数{},请求体参数{},是否开启代理{}",
                    url,
                    jsonObject,
                    params,
                    proxy);
            HttpPost httpPost = new HttpPost(url);
            return getResponse(httpPost, jsonObject, params, proxy);
        } catch (Exception e) {
            log.error("远程服务器异常!服务器地址{},请求头参数{},请求体参数{},是否开启代理{},异常内容{}",
                    url,
                    jsonObject,
                    params,
                    proxy,
                    e.getMessage());
            return "";
        }
    }

    /**
     * POST请求
     */
    public static String doPost(String url, String params, boolean proxy, boolean needSSL, Map<String, Object> sslParams) {
        try {
            log.error("远程服务器!服务器地址{}, 请求体参数{},是否开启代理{}, 是否需要SSL{},SSL参数{}",
                    url,
                    params,
                    proxy,
                    needSSL,
                    sslParams);
            HttpPost httpPost = new HttpPost(url);
            return getResponse(httpPost, params, proxy, needSSL, sslParams);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * doPut请求
     */
    public static String doPut(String url, Map<String, String> headerMap, String requestBody, boolean proxy) {
        String entityStr = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        //设置请求和传输超时时间
        //单位毫秒
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(3000).setConnectTimeout(3000)
                .setSocketTimeout(3000).build();//设置请求的状态参数
        try {
            HttpPut httpPut = new HttpPut(url);
            httpPut.setConfig(requestConfig);
            //添加头部信息
            for (Map.Entry<String, String> header : headerMap.entrySet()) {
                httpPut.addHeader(header.getKey(), header.getValue());
                httpPut.addHeader("Content-Type", "application/json;charset=utf-8");
            }
            HttpEntity entity = new StringEntity(requestBody, "Utf-8");
            log.info("请求体是:" + requestBody);
            httpPut.setEntity(entity);
            if (proxy) {
                response = httpClient.execute(httpPut, setProxy(httpPut));
            } else {
                response = httpClient.execute(httpPut);
            }
            // 获得响应的实体对象
            HttpEntity httpEntity = response.getEntity();
            // 使用Apache提供的工具类进行转换成字符串
            entityStr = EntityUtils.toString(httpEntity, "UTF-8");
            log.info("PUT请求路径:" + httpPut);
            log.info("PUT请求结果:" + entityStr);
        } catch (ClientProtocolException e) {
            log.info("Http协议出现问题");
            e.printStackTrace();
        } catch (ParseException e) {
            log.info("解析错误");
            e.printStackTrace();
        } catch (IOException e) {
            log.info("IO异常");
            e.printStackTrace();
        } catch (MalformedChallengeException e) {
            e.printStackTrace();
        }
        return entityStr;
    }

    /**
     * 短信发送接口
     */
    public static String doPost(String url, JSONObject header, JSONObject body, boolean proxy, int timeOut) {
        try {
            log.info("短信发送接口 地址:{},参数头:{},参数体:{},是否开启代理:{}, 超时时间:{}"
                    , url, header, body, proxy, timeOut);
            HttpPost httpPost = new HttpPost(url);
            return getResponse(httpPost, header, body, proxy, timeOut);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 短信发送
     */
    private static String getResponse(HttpPost httpPost, JSONObject header, JSONObject body, boolean proxy, int timeOut) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeOut).setConnectTimeout(timeOut).build();
        httpPost.addHeader("Authorization", header.getString("Authorization"));
        httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
        ByteArrayEntity entity = null;
        try {
            entity = new ByteArrayEntity(JSONObject.toJSONString(body).getBytes("UTF-8"));
            entity.setContentType("application/json");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("向服务器承保接口发起http请求,封装请求body时出现异常", e);
        }
        httpPost.setEntity(entity);
        httpPost.setConfig(requestConfig);
        log.info("请求信息:{}", httpPost);
        CloseableHttpResponse response = null;
        if (proxy) {
            response = httpClient.execute(httpPost, setProxy(httpPost));
        } else {
            response = httpClient.execute(httpPost);
        }
        return response(httpClient, response);
    }

    private static String getResponse(HttpPost httpPost, String params, boolean proxy) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();
        httpPost = getHttpPost(httpPost, params);
        httpPost.setConfig(requestConfig);
        CloseableHttpResponse response = null;
        if (proxy) {
            response = httpClient.execute(httpPost, setProxy(httpPost));
        } else {
            response = httpClient.execute(httpPost);
        }
        return response(httpClient, response);
    }

    private static String getResponse(HttpPost httpPost, JSONObject jsonObject, String params, boolean proxy) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();
        httpPost = getHttpPost(httpPost, params);
        httpPost.setConfig(requestConfig);
        for (String str : jsonObject.keySet()) {
            httpPost.setHeader(str, jsonObject.getString(str));
        }
        log.info("请求信息:{}" + httpPost);
        CloseableHttpResponse response = null;
        if (proxy) {
            response = httpClient.execute(httpPost, setProxy(httpPost));
        } else {
            response = httpClient.execute(httpPost);
        }
        return response(httpClient, response);
    }

    private static String getResponse(HttpPost httpPost, String params, boolean proxy, boolean needSSL, Map<String, Object> sslParams) throws Exception {
        CloseableHttpClient httpClient = null;
        if (needSSL) {
            String keyStoreStr = (String) sslParams.get("KEY_STORE");
            String serverName = (String) sslParams.get("SERVER_NAME");
            String basetruststoreName = (String) sslParams.get("BASETRUSTSTORE_NAME");
            String pfxPwdStr = (String) sslParams.get("PFX_PWD");
            String[] sslsfArr = (String[]) sslParams.get("SSL_SF");
            KeyStore serverKeyStore = null;
            KeyStore basetruststoreKeyStore = null;
            InputStream serverIs = null;
            InputStream basetruststoreIs = null;
            try {
                ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

                serverKeyStore = KeyStore.getInstance(keyStoreStr);
                serverIs = classLoader.getResourceAsStream(serverName);
                serverKeyStore.load(serverIs, pfxPwdStr.toCharArray());

                basetruststoreKeyStore = KeyStore.getInstance(keyStoreStr);
                basetruststoreIs = classLoader.getResourceAsStream(basetruststoreName);
                basetruststoreKeyStore.load(basetruststoreIs, pfxPwdStr.toCharArray());
            } catch (KeyStoreException e) {
                log.info("keyStore Load失败:", e);
            } finally {
                if (null != serverIs) {
                    serverIs.close();
                }
                if (null != basetruststoreIs) {
                    basetruststoreIs.close();
                }
            }
            SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(serverKeyStore, pfxPwdStr.toCharArray()).loadTrustMaterial(basetruststoreKeyStore, null).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext
                    , sslsfArr
                    , null
                    , SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            httpClient = HttpClients.custom()
                    .setSSLSocketFactory(sslsf)
                    .build();
            log.info("获取携带证书 httpClient成功");
        } else {
            log.info("获取非携带证书 httpClient成功");
            httpClient = HttpClients.createDefault();
        }
        //设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();
        httpPost = getHttpPost(httpPost, params);
        httpPost.setConfig(requestConfig);
        CloseableHttpResponse response = null;
        if (proxy) {
            response = httpClient.execute(httpPost, setProxy(httpPost));
        } else {
       /*     InputStream is = new ByteArrayInputStream(params.getBytes("UTF-8"));
            InputStreamEntity inputStreamEntity = new InputStreamEntity(is, is.available());
            httpPost.setEntity(inputStreamEntity);*/
            response = httpClient.execute(httpPost);
        }
        return response(httpClient, response);
    }

    private static HttpPost getHttpPost(HttpPost httpPost, String params) throws UnsupportedEncodingException {
        JSONObject jsonObject = JSONObject.parseObject(params);
        if (jsonObject.containsKey("bearerToken")) {
            httpPost.addHeader("Authorization", jsonObject.getString("bearerToken"));
            jsonObject.remove("bearerToken");
            params = JSONObject.toJSONString(jsonObject);
        } else if (jsonObject.containsKey("header")) {
            if ("onlineStore".equals(jsonObject.getString("header"))) {
                httpPost.addHeader("version", jsonObject.getString("version"));
                httpPost.addHeader("messageID", jsonObject.getString("messageID"));
                httpPost.addHeader("custCode", jsonObject.getString("custCode"));
                httpPost.addHeader("dateTimeStamp", jsonObject.getString("dateTimeStamp"));
                jsonObject.remove("header");
                jsonObject.remove("version");
                jsonObject.remove("messageID");
                jsonObject.remove("custCode");
                jsonObject.remove("dateTimeStamp");
                if (jsonObject.containsKey("token")) {
                    httpPost.addHeader("token", jsonObject.getString("token"));
                    jsonObject.remove("token");
                    httpPost.addHeader("encryptType", jsonObject.getString("encryptType"));
                    jsonObject.remove("encryptType");
                }
            } else if ("mobile".equals(jsonObject.getString("header"))) {
                httpPost.addHeader("accessToken", jsonObject.getString("accessToken"));
                httpPost.addHeader("requestId", jsonObject.getString("requestId"));
                jsonObject.remove("accessToken");
                jsonObject.remove("requestId");
            }
        }
        if (jsonObject.containsKey("formData")) {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            jsonObject.remove("formData");
            if (jsonObject != null) {
                for (String key : jsonObject.keySet()) {
                    builder.addPart(key,
                            new StringBody(jsonObject.getString(key), ContentType.create("text/plain", Consts.UTF_8)));
                }
            }
            HttpEntity reqEntity = builder.build();
            httpPost.setEntity(reqEntity);
        } else {
            httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
            httpPost.setEntity(new StringEntity(params, "UTF-8"));
        }
        log.info("请求params:{}", params);
        return httpPost;
    }

    private static String response(CloseableHttpClient httpClient, CloseableHttpResponse response) throws IOException {
        try {
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                String jsonString = EntityUtils.toString(responseEntity);
                log.info("返回应答:{}", jsonString);
                return jsonString;
            } else {
                String jsonString = EntityUtils.toString(response.getEntity());
                log.error("请求返回的数据:{}", jsonString);
            }
        } finally {
            // 释放资源
            if (httpClient != null) {
                httpClient.close();
            }
            if (response != null) {
                response.close();
            }
        }
        return "";
    }

    /**
     * 设置代理
     */
    private static HttpClientContext setProxy(HttpRequestBase httpRequestBase) throws MalformedChallengeException {
        HttpHost proxy = new HttpHost("192.168.0.1", 8080);
        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
        httpRequestBase.setConfig(config);
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
                new AuthScope(proxy),
                new UsernamePasswordCredentials("xxxx", "xxxx")
        );
        HttpClientContext context = HttpClientContext.create();
        context.setCredentialsProvider(credsProvider);
        return context;
    }
}

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,444评论 6 496
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,421评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,036评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,363评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,460评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,502评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,511评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,280评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,736评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,014评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,190评论 1 342
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,848评论 5 338
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,531评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,159评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,411评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,067评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,078评论 2 352

推荐阅读更多精彩内容