【无标题】

http远程调用工具类


package com.pcitc.base.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.
;
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.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
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.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ObjectUtils;

import javax.activation.MimetypesFileTypeMap;
import javax.net.ssl.;
import java.io.
;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.*;

public class HttpUtils {
private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);
private static final CloseableHttpClient httpClient;
private static final RequestConfig requestConfig;
static final String CHARSET = “UTF-8”;
//连接池最大并发连接数
private static final int MAX_TOTAL_CONNECTIONS = 2000;
//单路由最大并发数
private static final int MAX_ROUTE_CONNECTIONS = 2000;
//超时时间
private static final int CONNECT_TIMEOUT = 15000;
private static final int SOCKET_TIMEOUT = 15000;
private static final int CONNECTION_REQUEST_TIMEOUT = 15000;

/*
  配置http连接池
 */
static {
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(MAX_TOTAL_CONNECTIONS);
    cm.setDefaultMaxPerRoute(MAX_ROUTE_CONNECTIONS);
    httpClient = HttpClients.custom().setConnectionManager(cm).build();
    requestConfig = RequestConfig.custom().setSocketTimeout(SOCKET_TIMEOUT).setConnectTimeout(CONNECT_TIMEOUT)
            .setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT).build();
}


/**
 * post请求(Map方式)
 *
 * @param url     请求的url地址 ?之前的地址
 * @param params  请求的参数
 * @param charset 编码格式
 * @return 返回所请求接口的反馈信息
 */
public static String doPost(String url, Map<String, String> params, String charset) {
    logger.info(">>>>>>>>>>>>>doPost 请求url:{},参数:{},字符编码:{}", url, JSON.toJSONString(params), charset);
    if (StringUtils.isBlank(url)) {
        return null;
    }
    HttpPost httpPost = null;

    try {
        // 使用NameValuePairca格式进行接口请求参数的传递和拼装
        List<NameValuePair> pairs = null;
        if (params != null && !params.isEmpty()) {
            pairs = new ArrayList<>(params.size());
            for (Map.Entry<String, String> entry : params.entrySet()) {
                String value = entry.getValue();
                if (value != null) {
                    pairs.add(new BasicNameValuePair(entry.getKey(), value));
                }
            }
        }
        httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        if (pairs != null && pairs.size() > 0) {
            httpPost.setEntity(new UrlEncodedFormEntity(pairs, CHARSET));
        }
        long startTime = System.currentTimeMillis();
        CloseableHttpResponse response = httpClient.execute(httpPost);
        long endTime = System.currentTimeMillis();
        logger.info("{} spend time {} millis", url, (endTime - startTime));
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            httpPost.abort();
            throw new RuntimeException("HttpClient,error status code :" + statusCode);
        }
        HttpEntity entity = response.getEntity();
        String result = null;
        if (entity != null) {
            result = EntityUtils.toString(entity, "utf-8");
        }
        EntityUtils.consume(entity);
        response.close();
        logger.info("调用post请求接口,响应结果:{}", result);
        return result;
    } catch (IOException e) {
        httpPost.releaseConnection();
        e.printStackTrace();
    }
    return null;
}

/**
 * post请求(NameValuePair方式)
 *
 * @param url     请求的url地址 ?之前的地址
 * @param map     请求的参数
 * @param charset 编码格式
 * @return 返回所请求接口的反馈信息
 */
public static String doPost(String url, List<NameValuePair> map, String charset, Map<String, String> headerMap) {
    logger.info(">>>>>>>>>>>>>doPost 请求url:{},参数:{},字符编码:{},header:{}", url, JSON.toJSONString(map), charset, headerMap);
    CloseableHttpResponse response = null;
    if (StringUtils.isBlank(url)) {
        return null;
    }
    HttpPost httpPost = null;
    try {
        httpPost = createHttpPost(url, map);
        if (null != headerMap && !headerMap.isEmpty()) {
            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                httpPost.addHeader(entry.getKey(), entry.getValue());
            }
        }
        response = httpClient.execute(httpPost);
        String result = acquireResult(response, httpPost);
        logger.info("调用post请求接口,响应结果:{}", result);
        return result;
    } catch (Exception e) {
        logger.error("do post error ", e);
    } finally {
        close(response);
        if (httpPost != null) {
            httpPost.releaseConnection();
        }
    }
    return null;
}

/**
 * POST请求,参数在url上
 *
 * @param url       请求url
 * @param urlParams url参数
 * @param charset   字符编码
 * @param headerMap 请求头
 * @return String 服务器返回数据
 */
public static String doPost(String url, Map<String, String> urlParams, String charset, Map<String, String> headerMap, RequestConfig requestConfig) {
    logger.info(">>>>>>>>>>>>>doPost 请求 url:{},url参数:{},字符编码:{}", url, JSON.toJSONString(urlParams), charset);
    if (StringUtils.isBlank(url)) {
        return null;
    }
    CloseableHttpResponse response = null;
    HttpPost httpPost = null;

    try {
        url = getString(url, urlParams, charset);
        httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        if (null != headerMap && !headerMap.isEmpty()) {
            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                httpPost.addHeader(entry.getKey(), entry.getValue());
            }
        }
        response = httpClient.execute(httpPost);
        return acquireResult(response, httpPost);

    } catch (IOException e) {
        if (null != httpPost) {
            httpPost.releaseConnection();
        }
        logger.error("<<<<<<<<<<<<<doPost 请求失败:{}", urlParams, e);
    }
    logger.info("调用post请求接口,响应结果:{}", response);
    return null;
}

private static String getString(String url, Map<String, String> urlParams, String charset) throws IOException {
    if (urlParams != null && !urlParams.isEmpty()) {
        List<NameValuePair> pairs = new ArrayList<>(urlParams.size());
        for (Map.Entry<String, String> entry : urlParams.entrySet()) {
            String value = entry.getValue();
            if (value != null) {
                pairs.add(new BasicNameValuePair(entry.getKey(), value));
            }
        }
        url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
    }
    return url;
}

/**
 * Get请求(Map方式)
 *
 * @param url    请求的url地址 ?之前的地址
 * @param params 请求的参数
 * @return 返回所请求接口的反馈信息
 */
public static String doGet(String url, Map<String, Object> params, Map<String, String> headerMap) {
    logger.info(">>>>>>>>>>>>>doGet 请求 url:{},参数:{},字符编码:{}", url, JSON.toJSONString(params), HttpUtils.CHARSET);
    if (StringUtils.isBlank(url)) {
        return null;
    }
    HttpGet httpGet = null;

    try {
        if (params != null && !params.isEmpty()) {
            List<NameValuePair> pairs = new ArrayList<>(params.size());
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                String value = null;
                if(!ObjectUtils.isEmpty(entry.getValue())){
                    value = String.valueOf(entry.getValue());
                }
                if (value != null) {
                    pairs.add(new BasicNameValuePair(entry.getKey(), value));
                }
            }
            url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, HttpUtils.CHARSET));
        }
        httpGet = new HttpGet(url);
        httpGet.setConfig(requestConfig);
        if (null != headerMap && !headerMap.isEmpty()) {
            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                httpGet.addHeader(entry.getKey(), entry.getValue());
            }
        }
        //跳过证书认证
        CloseableHttpClient httpClient = wrapClient(url, null);

        CloseableHttpResponse response = httpClient.execute(httpGet);
        int statusCode = response.getStatusLine().getStatusCode();

// if (statusCode != 200) {
// httpGet.abort();
// throw new RuntimeException(“HttpClient,error status code :” + statusCode);
// }
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, “utf-8”);
}
EntityUtils.consume(entity);
response.close();
logger.info(“>>>>>>>>>>>>>doGet 返回:{}”, result);
return result;
} catch (IOException e) {
if (null != httpGet) {
httpGet.releaseConnection();
}
logger.error(“<<<<<<<<<<<<<doGet 请求失败:{}”, params, e);
}
return null;
}

/**
 * Get请求(NameValuePair方式)
 *
 * @param url     请求的url地址 ?之前的地址
 * @param params  请求的参数
 * @param charset 编码格式
 * @return 返回所请求接口的反馈信息
 */
public static String doGet(String url, List<NameValuePair> params, String charset) {
    logger.info(">>>>>>>>>>>>>doGet 请求url :{},参数:{},字符编码:{}", url, JSON.toJSONString(params), charset);
    CloseableHttpResponse response = null;
    if (StringUtils.isBlank(url)) {
        return null;
    }
    HttpGet httpGet = null;
    try {
        if (params != null && !params.isEmpty()) {
            url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(params, charset));
        }
        httpGet = createHttpGet(url);
        response = httpClient.execute(httpGet);
        return acquireResult(response, httpGet);
    } catch (Exception e) {
        logger.error("do get error ", e);
    } finally {
        close(response);
        if (httpGet != null) {
            httpGet.releaseConnection();
        }
    }
    logger.info("调用get请求接口,响应结果:{}", response);
    return null;
}

public static String doGet(String url, Map<String, Object> params) {
    return doGet(url, params, null);
}

public static String doPost(String url, Map<String, String> params) {
    return doPost(url, params, CHARSET);
}


/***
 * 获取Http Get/Post请求中返回的数据
 * @param response    服务器返回response
 * @param requestBase HttpGet/HttpPost 对象
 *
 * @return String 服务器返回数据
 * */
private static String acquireResult(CloseableHttpResponse response, HttpRequestBase requestBase) throws IOException {
    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode != HttpStatus.SC_OK) {
        requestBase.abort();
        throw new RuntimeException("HttpClient,error status code :" + statusCode);
    }
    HttpEntity entity = response.getEntity();
    String result = null;
    if (entity != null) {
        result = EntityUtils.toString(entity, "utf-8");
    }
    EntityUtils.consume(entity);
    return result;
}

private static HttpPost createHttpPost(String url, List<NameValuePair> pairs) {
    HttpPost post = new HttpPost(url);
    post.setConfig(requestConfig);
    try {
        if (pairs != null && pairs.size() > 0) {
            post.setEntity(new UrlEncodedFormEntity(pairs, CHARSET));
        }
    } catch (Exception e) {
        logger.error("create http post error ", e);
    }
    return post;
}

private static HttpGet createHttpGet(String url) {
    HttpGet get = new HttpGet(url);
    get.setConfig(requestConfig);
    return get;
}


/**
 * 调用post请求接口
 *
 * @param url  发送的服务器地址
 * @param json 请求的json报文
 * @return 响应结果JSON对象
 */
public static JSONObject doPostOfJson(String url, JSONObject json) {
    logger.info("调用post请求接口,请求地址:{},请求参数:{}", url, json);
    CloseableHttpClient httpclient = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(url);
    JSONObject response = null;
    try {
        StringEntity s = new StringEntity(json.toString(), "utf-8");
        s.setContentEncoding("UTF-8");
        //发送json数据需要设置contentType
        s.setContentType("application/json;charset=UTF-8");
        post.setEntity(s);
        HttpResponse res = httpclient.execute(post);
        if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            // 返回json格式:
            String result = EntityUtils.toString(res.getEntity(), "utf-8");
            response = JSONObject.parseObject(result);
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
    logger.info("调用post请求接口,响应结果:{}", response);
    return response;
}

public static String doPutOfJson(String url, JSONObject json) {
    logger.info("调用put请求接口,请求地址:{},请求参数:{}", url, json);
    CloseableHttpClient httpclient = HttpClientBuilder.create().build();
    HttpPut httpPut = new HttpPut(url);
    String resultString = "";
    int statusCode = 200;
    try {
        StringEntity s = new StringEntity(json.toString(), "utf-8");
        s.setContentEncoding("UTF-8");
        //发送json数据需要设置contentType
        s.setContentType("application/json;charset=UTF-8");
        httpPut.setEntity(s);
        HttpResponse res = httpclient.execute(httpPut);
        statusCode = res.getStatusLine().getStatusCode();
        // 返回json格式:
        resultString = EntityUtils.toString(res.getEntity(), "utf-8");

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
    logger.info("调用put请求接口,HTTP状态码:{},响应结果:{}", statusCode, resultString);
    return resultString;
}

public static String doPostString(String url, JSONObject json) {
    logger.info("调用post请求接口,请求地址:{},请求参数:{}", url, json);
    CloseableHttpClient httpclient = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(url);
    String response = null;
    int statusCode = 200;
    try {
        StringEntity s = new StringEntity(json.toString(), "utf-8");
        s.setContentEncoding("UTF-8");
        //发送json数据需要设置contentType
        s.setContentType("application/json;charset=UTF-8");
        post.setEntity(s);
        HttpResponse res = httpclient.execute(post);
        statusCode = res.getStatusLine().getStatusCode();
        // 返回json格式:
        response = EntityUtils.toString(res.getEntity(), "utf-8");
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
    logger.info("调用put请求接口,HTTP状态码:{},响应结果:{}", statusCode, response);
    return response;
}

public static JSONObject doPostWithHeader(String url, String json, Map<String, String> headerMap) {
    logger.info("调用post请求接口,请求地址:{},请求参数:{}", url, json);
    CloseableHttpClient httpclient = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(url);
    JSONObject response = null;
    try {
        StringEntity s = new StringEntity(json, "UTF-8");
        s.setContentEncoding("UTF-8");
        s.setContentType("application/json;charset=utf-8");
        post.setEntity(s);
        if (null != headerMap && !headerMap.isEmpty()) {
            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                post.addHeader(entry.getKey(), entry.getValue());
            }
        }
        HttpResponse res = httpclient.execute(post);
        if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String result = EntityUtils.toString(res.getEntity());
            response = JSONObject.parseObject(result);
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
    logger.info("调用post请求接口,响应结果:{}", response);
    return response;
}

public static String doDelete(String url, Map<String, Object> params) {
    logger.info(">>>>>>>>>>>>>doDelete 请求 url:{},参数:{},字符编码:{}", url, JSON.toJSONString(params), HttpUtils.CHARSET);
    if (StringUtils.isBlank(url)) {
        return null;
    }
    HttpDelete httpDelete = null;
    try {
        if (params != null && !params.isEmpty()) {
            List<NameValuePair> pairs = new ArrayList<>(params.size());
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                String value = (String) entry.getValue();
                if (value != null) {
                    pairs.add(new BasicNameValuePair(entry.getKey(), value));
                }
            }
            url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, HttpUtils.CHARSET));
        }
        httpDelete = new HttpDelete(url);
        httpDelete.setConfig(requestConfig);
        CloseableHttpResponse response = httpClient.execute(httpDelete);
        int statusCode = response.getStatusLine().getStatusCode();
        HttpEntity entity = response.getEntity();
        String result = null;
        if (entity != null) {
            result = EntityUtils.toString(entity, "utf-8");
        }
        EntityUtils.consume(entity);
        response.close();
        logger.info(">>>>>>>>>>>>>doDelete HTTP状态码:{}, 返回:{}", statusCode, result);
        return result;
    } catch (IOException e) {
        if (null != httpDelete) {
            httpDelete.releaseConnection();
        }
        logger.error("<<<<<<<<<<<<<doDelete 请求失败:{}", params, e);
    }
    return null;
}

/**
 * 创建一个用于basic auth验证的请求头
 *
 * @param headerMap 请求头
 * @param username  用户名
 * @param password  密码
 * @return map
 */
public static Map<String, String> createBasicAuthHeader(Map<String, String> headerMap,
                                                        String username, String password) {
    if (MapUtils.isEmpty(headerMap)) {
        headerMap = new HashMap<>();
    }
    headerMap.put("Authorization", "Basic " + Base64
            .getUrlEncoder().encodeToString((username + ":" + password).getBytes()));
    return headerMap;
}

public static void close(Closeable closeable) {
    if (null != closeable) {
        try {
            closeable.close();
        } catch (IOException var2) {
            logger.error("Close closeable faild: " + closeable.getClass(), var2);
        }
    }

}

/**
 * @param url
 * @param jsonString
 * @param charset
 * @param headerMap
 * @return java.lang.String
 * @Author huo
 * @Description json格式post
 * @Date 14:57 2021/7/7
 **/
public static String post(String url, String jsonString, String charset, Map<String, String> headerMap) {
    logger.info(">>>>>>>>>>>>>doPost 请求url:{},参数:{},字符编码:{},header:{}", url, jsonString, charset, headerMap);
    CloseableHttpResponse response = null;
    BufferedReader in = null;
    String result = "";
    HttpPost httpPost = null;
    try {
        //跳过证书认证
        CloseableHttpClient httpClient = wrapClient(url, null);

        httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setConnectionRequestTimeout(30000).setSocketTimeout(30000).build();
        httpPost.setConfig(requestConfig);
        httpPost.setConfig(requestConfig);
        if (null != headerMap && !headerMap.isEmpty()) {
            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                httpPost.addHeader(entry.getKey(), entry.getValue());
            }
        }
        httpPost.setEntity(new StringEntity(jsonString, Charset.forName(charset)));
        response = httpClient.execute(httpPost);
        result = acquireResult(response, httpPost);
        logger.info("调用post请求接口,响应结果:{}", result);
        return result;
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        close(response);
        if (httpPost != null) {
            httpPost.releaseConnection();
        }
    }
    return null;
}

/**
 * @param urlStr
 * @param textMap
 * @param fileMap
 * @param headersMaps
 * @param contentType
 * @return java.lang.String
 * @Author huo
 * @Description 文件上传
 * @Date 10:49 2021/7/8
 **/
@SuppressWarnings("rawtypes")
public static String formUpload(String urlStr, Map<String, String> textMap,
                                Map<String, String> fileMap, Map<String, String> headersMaps, String contentType) {
    logger.info(">>>>>>>>>>>>>doPost 请求url:{},参数:{},文件参数:{},contentType:{},header:{}", urlStr, JSON.toJSONString(textMap), JSON.toJSONString(fileMap), contentType, JSON.toJSONString(headersMaps));
    String res = "";
    HttpURLConnection conn = null;
    // boundary就是request头和上传文件内容的分隔符
    String BOUNDARY = "---------------------------123821742118716";
    try {
        //该部分必须在获取connection前调用 java访问https资源时,忽略证书信任问题
        trustAllHttpsCertificates();
        HostnameVerifier hv = new HostnameVerifier() {
            @Override
            public boolean verify(String urlHostName, SSLSession session) {
                logger.info("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
                return true;
            }
        };
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
        URL url = new URL(urlStr);
        conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(30000);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        // conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
        HttpURLConnection finalConn = conn;
        headersMaps.forEach((k, v) -> {
            finalConn.setRequestProperty(k, v);
        });
        OutputStream out = new DataOutputStream(conn.getOutputStream());
        // text
        if (textMap != null) {
            StringBuffer strBuf = new StringBuffer();
            Iterator iter = textMap.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                String inputName = (String) entry.getKey();
                String inputValue = (String) entry.getValue();
                if (inputValue == null) {
                    continue;
                }
                strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
                strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n");
                strBuf.append(inputValue);
            }
            out.write(strBuf.toString().getBytes());
        }
        // file
        if (fileMap != null && !fileMap.isEmpty()) {
            Iterator iter = fileMap.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                String inputName = (String) entry.getKey();
                String inputValue = (String) entry.getValue();
                if (inputValue == null) {
                    continue;
                }
                File file = new File(inputValue);
                String filename = file.getName();

                //没有传入文件类型,同时根据文件获取不到类型,默认采用application/octet-stream
                contentType = new MimetypesFileTypeMap().getContentType(file);
                //contentType非空采用filename匹配默认的图片类型
                if (!"".equals(contentType)) {
                    if (filename.endsWith(".png")) {
                        contentType = "image/png";
                    } else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".jpe")) {
                        contentType = "image/jpeg";
                    } else if (filename.endsWith(".gif")) {
                        contentType = "image/gif";
                    } else if (filename.endsWith(".ico")) {
                        contentType = "image/image/x-icon";
                    }
                }
                if (contentType == null || "".equals(contentType)) {
                    contentType = "application/octet-stream";
                }
                StringBuffer strBuf = new StringBuffer();
                strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
                strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename + "\"\r\n");
                strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
                out.write(strBuf.toString().getBytes());
                DataInputStream in = new DataInputStream(new FileInputStream(file));
                int bytes = 0;
                byte[] bufferOut = new byte[1024];
                while ((bytes = in.read(bufferOut)) != -1) {
                    out.write(bufferOut, 0, bytes);
                }
                in.close();
            }
        }
        byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
        out.write(endData);
        out.flush();
        out.close();
        // 读取返回数据
        StringBuffer strBuf = new StringBuffer();
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line = null;
        while ((line = reader.readLine()) != null) {

// strBuf.append(line).append(“\n”);
strBuf.append(line);
}
res = strBuf.toString();
logger.info(“调用post请求接口,响应结果:{}”, res);
reader.close();
reader = null;
} catch (Exception e) {
System.out.println(“发送POST请求出错。” + urlStr);
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
return res;
}

public static Map<String,Object> doGetFile(String url, Map<String, Object> params, Map<String, String> headerMap) {
    logger.info(">>>>>>>>>>>>>doGetFile 请求 url:{},参数:{},字符编码:{}", url, JSON.toJSONString(params), HttpUtils.CHARSET);
    if (StringUtils.isBlank(url)) {
        return null;
    }
    HttpGet httpGet = null;

    try {
        if (params != null && !params.isEmpty()) {
            List<NameValuePair> pairs = new ArrayList<>(params.size());
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                String value = String.valueOf(entry.getValue());
                if (value != null) {
                    pairs.add(new BasicNameValuePair(entry.getKey(), value));
                }
            }
            url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, HttpUtils.CHARSET));
        }
        //跳过证书认证
        CloseableHttpClient httpClient = wrapClient(url, null);

        httpGet = new HttpGet(url);
        httpGet.setConfig(requestConfig);
        if (null != headerMap && !headerMap.isEmpty()) {
            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                httpGet.addHeader(entry.getKey(), entry.getValue());
            }
        }
        CloseableHttpResponse response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        String fileName = getFileName(response);
        logger.info(">>>>>>>>>>>>>doGetFile[{}] 请求成功",fileName);
        Map<String,Object> rspMap = new HashMap<>();
        rspMap.put("fileName",fileName);
        rspMap.put("fileInputStream",entity.getContent());
        return rspMap;
    } catch (IOException e) {
        if (null != httpGet) {
            httpGet.releaseConnection();
        }
        logger.error("<<<<<<<<<<<<<doGet 请求失败:{}", params, e);
    }
    return null;
}

/**
 * 获取response header中Content-Disposition中的filename值
 *
 * @param response
 * @return
 */
public static String getFileName(HttpResponse response) {
    Header contentHeader = response.getFirstHeader("Content-Disposition");
    String filename = null;
    if (contentHeader != null) {
        HeaderElement[] values = contentHeader.getElements();
        if (values.length == 1) {
            NameValuePair param = values[0].getParameterByName("filename");
            if (param != null) {
                try {
                    //filename = new String(param.getValue().toString().getBytes(), "utf-8");
                    //filename=URLDecoder.decode(param.getValue(),"utf-8");
                    filename = param.getValue();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
    return filename;
}

/**
 * 获取 HttpClient
 *
 * @param host
 * @param path
 * @return
 */
private static CloseableHttpClient wrapClient(String host, String path) {
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    if (host != null && host.startsWith("https://")) {
        return sslClient();
    } else if (StringUtils.isBlank(host) && path != null && path.startsWith("https://")) {
        return sslClient();
    }
    return httpClient;
}

/**
 * 在调用SSL之前需要重写验证方法,取消检测SSL
 * 创建ConnectionManager,添加Connection配置信息
 *
 * @return HttpClient 支持https
 */
private static CloseableHttpClient sslClient() {
    try {
        // 在调用SSL之前需要重写验证方法,取消检测SSL
        X509TrustManager trustManager = new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkClientTrusted(X509Certificate[] xcs, String str) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] xcs, String str) {
            }
        };
        SSLContext ctx = SSLContext.getInstance(SSLConnectionSocketFactory.TLS);
        ctx.init(null, new TrustManager[]{trustManager}, null);
        SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
        // 创建Registry
        RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT)
                .setExpectContinueEnabled(Boolean.TRUE).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
                .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                .register("https", socketFactory).build();
        // 创建ConnectionManager,添加Connection配置信息
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        CloseableHttpClient closeableHttpClient = HttpClients.custom().setConnectionManager(connectionManager)
                .setDefaultRequestConfig(requestConfig).build();
        return closeableHttpClient;
    } catch (KeyManagementException ex) {
        throw new RuntimeException(ex);
    } catch (NoSuchAlgorithmException ex) {
        throw new RuntimeException(ex);
    }
}

private static void trustAllHttpsCertificates() throws Exception {
    javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
    javax.net.ssl.TrustManager tm = new miTM();
    trustAllCerts[0] = tm;
    javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, null);
    javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}

static class miTM implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {
    @Override
    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
        return null;
    }

    public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) {
        return true;
    }

    public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) {
        return true;
    }

    @Override
    public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
            throws java.security.cert.CertificateException {
        return;
    }

    @Override
    public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
            throws java.security.cert.CertificateException {
        return;
    }
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值