java项目中调用外部接口工具类-HttpUtils

项目中调用外部接口工具类

package com.common.utils;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ContentBody;
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.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.io.*;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

public class HttpUtils {
    public static Logger logger = LoggerFactory.getLogger(HttpUtil.class);
    private static CloseableHttpClient singletonHttpsClient = null;
    private static CloseableHttpClient defaultHttpClient = null;

    static {
        singletonHttpsClient = getSingletonHttpsClient();
        defaultHttpClient = HttpClients.createDefault();
    }

    /**
     * 单向httpsClient
     * @return
     */
    public static CloseableHttpClient getSingletonHttpsClient(){
        // 创建一个注册工厂, 用来注册http/https请求
        RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create();
        ConnectionSocketFactory socketFactory = new PlainConnectionSocketFactory();
        // 注册http请求
        registryBuilder.register("http", socketFactory);

        try {
            // 实例化一个keyStore认证库
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            // 信任所有
            TrustStrategy anyTrustStrategy = (x509Certificate, s) -> true;
            // 信任所有host
            HostnameVerifier verifier = (s, sslSession) -> true;
            // KeyStore&TrustStrategy加载到ssl上下文
            SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(trustStore, anyTrustStrategy).build();
            // 此方法是生成一个Socket工厂,https请求在真实请求接口前,需提前发起socket请求验证,参数是ssl上下文以及信任所有host的方法
            LayeredConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(sslContext, verifier);
            // 注册https请求
            registryBuilder.register("https", sslSF);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
        Registry<ConnectionSocketFactory> registry = registryBuilder.build();
        // 设置连接管理器
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
        // 返回生成的CloseableHttpClient
        return HttpClientBuilder.create().setConnectionManager(connectionManager).build();
    }

    /**
     * post请求(text/plain)
     * @param url
     * @param data
     * @param headerParam
     * @param charset
     * @return
     */
    public static String doPost(String url, String data, JSONObject headerParam, String charset) {
        CloseableHttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try {
            if(url.contains("https")){
                httpClient = singletonHttpsClient;
            } else {
                httpClient = defaultHttpClient;
            }
            httpPost = new HttpPost(url);
            // 设置头部参数
            if(headerParam != null){
                for(String key : headerParam.keySet()){
                    httpPost.addHeader(key, headerParam.getString(key));
                }
                if(!headerParam.containsKey("Content-Type")){
                    httpPost.addHeader("Content-Type", "text/plain;charset=utf-8");
                }
                if(!headerParam.containsKey("Content-Length")){
                    //httpPost.addHeader("Content-Length", String.valueOf(data.length()));
                }
            } else {
                httpPost.addHeader("Content-Type", "text/plain;charset=utf-8");
                //httpPost.addHeader("Content-Length", String.valueOf(data.length()));
            }
            StringEntity entity = new StringEntity(data, charset);
            entity.setContentEncoding(charset);
            httpPost.setEntity(entity);
            CloseableHttpResponse response = httpClient.execute(httpPost);
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity, charset);
                }
                response.close();
            }
        } catch (Exception e){
            logger.error("httpUtil do post fail:{}",e.getMessage());
        }
        return result;
    }

    /**
     * post请求(multipart/form-data)
     * @param url
     * @param paramBody
     * @param headerParam
     * @param boundary
     * @param charset
     * @return
     */
    public static String doPost(String url, Map<String, ContentBody> paramBody, JSONObject headerParam, String boundary, String charset) {
        CloseableHttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try {
            if(url.contains("https")){
                httpClient = singletonHttpsClient;
            } else {
                httpClient = defaultHttpClient;
            }
            httpPost = new HttpPost(url);
            // 设置头部参数
            if(headerParam != null){
                for(String key : headerParam.keySet()){
                    if(headerParam.containsKey("Content-Type")){
                        continue;
                    }
                    httpPost.addHeader(key, headerParam.getString(key));
                }
                if(!headerParam.containsKey("Content-Length")){
                    //httpPost.addHeader("Content-Length", String.valueOf(data.length()));
                }
            } else {
                //httpPost.addHeader("Content-Length", String.valueOf(data.length()));
            }
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            multipartEntityBuilder.setCharset(Charset.forName(charset));
            if(StringUtils.isNotBlank(boundary)){
                multipartEntityBuilder.setBoundary(boundary);
            }
            if(paramBody != null){
                for(Map.Entry<String, ContentBody> entry : paramBody.entrySet()){
                    multipartEntityBuilder.addPart(entry.getKey(), entry.getValue());
                }
            }
            HttpEntity entity = multipartEntityBuilder.build();
            httpPost.setEntity(entity);
            CloseableHttpResponse response = httpClient.execute(httpPost);
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity, charset);
                }
                response.close();
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    public static HttpResponse doPostByResponse(String url, String data, JSONObject headerParam, String charset) {
        CloseableHttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try {
            if(url.contains("https")){
                httpClient = singletonHttpsClient;
            } else {
                httpClient = defaultHttpClient;
            }
            //httpClient = HttpClients.custom().setSSLSocketFactory(getSSLConnectionSocketFactory()).build();
            httpPost = new HttpPost(url);
            // 设置头部参数
            if(headerParam != null){
                for(String key : headerParam.keySet()){
                    httpPost.addHeader(key, headerParam.getString(key));
                }
                if(!headerParam.containsKey("Content-Type")){
                    httpPost.addHeader("Content-Type", "text/plain;charset=utf-8");
                }
                if(!headerParam.containsKey("Content-Length")){
                    httpPost.addHeader("Content-Length", String.valueOf(data.length()));
                }
            } else {
                httpPost.addHeader("Content-Type", "text/plain;charset=utf-8");
                httpPost.addHeader("Content-Length", String.valueOf(data.length()));
            }
            StringEntity entity = new StringEntity(data, charset);
            entity.setContentEncoding(charset);
            httpPost.setEntity(entity);
            return httpClient.execute(httpPost);
        } catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * post请求(text/plain)
     * @param url
     * @param data
     * @param charset
     * @return
     */
    public static String doPost(String url, String data, String charset) {
        CloseableHttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try {
            if(url.contains("https")){
                httpClient = singletonHttpsClient;
            } else {
                httpClient = defaultHttpClient;
            }
            httpPost = new HttpPost(url);
            // 设置头部参数
            httpPost.addHeader("Content-Type", "text/plain;charset=utf-8");
            StringEntity entity = new StringEntity(data, charset);
            entity.setContentEncoding(charset);
            httpPost.setEntity(entity);
            CloseableHttpResponse response = httpClient.execute(httpPost);
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity, charset);
                }
                response.close();
            }

        } catch (Exception e){
            logger.error("httpUtil do post fail:{}",e.getMessage());
        }
        return result;
    }

    /**
     * get请求(multipart/form-data)
     * @param url
     * @param headerParam
     * @param charset
     * @return
     */
    public static String doGet(String url, JSONObject headerParam, String charset) {
        CloseableHttpClient httpClient = null;
        HttpGet httpGet = null;
        String result = null;
        try {
            if(url.contains("https")){
                httpClient = singletonHttpsClient;
            } else {
                httpClient = defaultHttpClient;
            }
            httpGet = new HttpGet(url);
            // 设置头部参数
            if(headerParam != null){
                for(String key : headerParam.keySet()){
                    if(headerParam.containsKey("Content-Type")){
                        continue;
                    }
                    httpGet.addHeader(key, headerParam.getString(key));
                }
                if(!headerParam.containsKey("Content-Length")){
                    //httpPost.addHeader("Content-Length", String.valueOf(data.length()));
                }
            } else {
                //httpPost.addHeader("Content-Length", String.valueOf(data.length()));
            }

            CloseableHttpResponse response = httpClient.execute(httpGet);
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity, charset);
                }
                response.close();
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    /**
     * get请求(text/plain)
     * @param url
     * @param charset
     * @return
     */
    public static String doGet(String url, String charset) {
        CloseableHttpClient httpClient = null;
        HttpGet httpGet = null;
        String result = null;
        try {
            if(url.contains("https")){
                httpClient = singletonHttpsClient;
            } else {
                httpClient = defaultHttpClient;
            }
            httpGet = new HttpGet(url);
            // 设置头部参数
            httpGet.addHeader("Content-Type", "text/plain;charset=utf-8");
            CloseableHttpResponse response = httpClient.execute(httpGet);
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity, charset);
                }
                response.close();
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    /**
     * post请求下载文件
     * @param url
     * @param data
     * @param headerParam
     * @param localPath
     * @return
     */
    public static boolean doPostDownLoadFile(String url, String data, JSONObject headerParam, String localPath) {
        CloseableHttpClient httpClient = null;
        HttpPost httpPost = null;
        boolean result = false;
        try {
            if(url.contains("https")){
                httpClient = singletonHttpsClient;
            } else {
                httpClient = defaultHttpClient;
            }
            httpPost = new HttpPost(url);
            // 设置头部参数
            if(headerParam != null){
                for(String key : headerParam.keySet()){
                    httpPost.addHeader(key, headerParam.getString(key));
                }
                if(!headerParam.containsKey("Content-Type")){
                    httpPost.addHeader("Content-Type", "text/plain;charset=utf-8");
                }
                if(!headerParam.containsKey("Content-Length")){
                    //httpGet.addHeader("Content-Length", String.valueOf(data.length()));
                }
            } else {
                httpPost.addHeader("Content-Type", "text/plain;charset=utf-8");
                // httpGet.addHeader("Content-Length", String.valueOf(data.length()));
            }
            StringEntity entity = new StringEntity(data, "UTF-8");
            entity.setContentEncoding("UTF-8");
            httpPost.setEntity(entity);
            CloseableHttpResponse response = httpClient.execute(httpPost);
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    InputStream is = resEntity.getContent();
                    File file = new File(localPath);
                    FileOutputStream fos = new FileOutputStream(file);
                    byte[] buffer = new byte[1024];
                    int len = 0;
                    while((len = is.read(buffer)) != -1){
                        fos.write(buffer, 0, len);
                    }
                    fos.close();
                    is.close();
                    result = true;
                }
                response.close();
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    /**
     * get请求下载文件
     * @param url
     * @param headerParam
     * @param localPath
     * @return
     */
    public static boolean doGetDownLoadFile(String url, JSONObject headerParam, String localPath) {
        CloseableHttpClient httpClient = null;
        HttpGet httpGet = null;
        boolean result = false;
        try {
            if(url.contains("https")){
                httpClient = singletonHttpsClient;
            } else {
                httpClient = defaultHttpClient;
            }
            httpGet = new HttpGet(url);
            // 设置头部参数
            if(headerParam != null){
                for(String key : headerParam.keySet()){
                    httpGet.addHeader(key, headerParam.getString(key));
                }
                if(!headerParam.containsKey("Content-Type")){
                    httpGet.addHeader("Content-Type", "text/plain;charset=utf-8");
                }
                if(!headerParam.containsKey("Content-Length")){
                    //httpGet.addHeader("Content-Length", String.valueOf(data.length()));
                }
            } else {
                httpGet.addHeader("Content-Type", "text/plain;charset=utf-8");
                // httpGet.addHeader("Content-Length", String.valueOf(data.length()));
            }
            CloseableHttpResponse response = httpClient.execute(httpGet);
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    InputStream is = resEntity.getContent();
                    File file = new File(localPath);
                    FileOutputStream fos = new FileOutputStream(file);
                    byte[] buffer = new byte[1024];
                    int len = 0;
                    while((len = is.read(buffer)) != -1){
                        fos.write(buffer, 0, len);
                    }
                    fos.close();
                    is.close();
                    result = true;
                }
                response.close();
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }
    
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值