JAVA远程请求工具类

import com.alibaba.fastjson.JSONObject;
import org.apache.http.Consts;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
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.client.methods.HttpPut;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
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.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * rest接口调用
 */
@Component
public class RestRequest implements Serializable {

    private static final long serialVersionUID = -7524694638614823508L;

    /**
     * get请求
     *
     * @param url          请求地址
     * @param headerParams 请求头参数
     * @param clazz        返回对象类型
     */
    public <T> T doGetRequest(String url, Map<String, String> headerParams, Class<T> clazz) throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        T result = null;
        if (null != headerParams && !headerParams.isEmpty()) {
            for (Map.Entry<String, String> param : headerParams.entrySet()) {
                httpGet.addHeader(param.getKey(), param.getValue());
            }
        }
        CloseableHttpResponse response = httpclient.execute(httpGet);
        int code = response.getStatusLine().getStatusCode();
        if (HttpStatus.SC_OK == code) {
            String responseStr = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
            try{
                result = JSONObject.parseObject(responseStr, clazz);
            } catch (Exception e){
                result = (T) responseStr;
            }
        }
        return result;
    }

    /**
     * post请求
     *
     * @param url          请求地址
     * @param headerParams 请求头参数
     * @param requestBody  请求参数
     * @param clazz        返回对象类型
     */
    public <T> T doPostRequest(String url, Map<String, String> headerParams, String requestBody, Class<T> clazz)
            throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        T result = null;
        if (null != headerParams && !headerParams.isEmpty()) {
            for (Map.Entry<String, String> param : headerParams.entrySet()) {
                httpPost.addHeader(param.getKey(), param.getValue());
            }
        }
        if (null != requestBody) {
            StringEntity stringEntity = new StringEntity(requestBody, ContentType.APPLICATION_JSON);
            httpPost.setEntity(stringEntity);
        }
        HttpResponse response = httpclient.execute(httpPost);
        int code = response.getStatusLine().getStatusCode();
        if (code == HttpStatus.SC_OK) {
            String responseStr = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
            result = JSONObject.parseObject(responseStr, clazz);
        }
        return result;
    }

    /**
     * post请求FormData参数
     *
     * @param url    请求地址
     * @param params 请求参数
     * @param clazz  返回对象类型
     */
    public <T> T doPostFormRequest(String url, Map<String, String> params, Class<T> clazz)
            throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        T result = null;
        if (null != params && !params.isEmpty()) {
            List<NameValuePair> paraList = new ArrayList<>();
            for (Map.Entry<String, String> param : params.entrySet()) {
                paraList.add(new BasicNameValuePair(param.getKey(), param.getValue()));
            }
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(paraList, StandardCharsets.UTF_8);
            httpPost.setEntity(urlEncodedFormEntity);
        }
        HttpResponse response = httpclient.execute(httpPost);
        int code = response.getStatusLine().getStatusCode();
        if (code == HttpStatus.SC_OK) {
            String responseStr = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
            result = JSONObject.parseObject(responseStr, clazz);
        }
        return result;
    }

    /**
     * put请求
     *
     * @param url          请求地址
     * @param headerParams 请求头参数
     * @param requestBody  请求参数
     * @param clazz        返回对象类型
     */
    public <T> T doPutRequest(String url, Map<String, String> headerParams, String requestBody, Class<T> clazz)
            throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPut httpPut = new HttpPut(url);
        T result = null;
        if (null != headerParams && !headerParams.isEmpty()) {
            for (Map.Entry<String, String> param : headerParams.entrySet()) {
                httpPut.addHeader(param.getKey(), param.getValue());
            }
        }
        if (null != requestBody) {
            StringEntity stringEntity = new StringEntity(requestBody, ContentType.APPLICATION_JSON);
            httpPut.setEntity(stringEntity);
        }
        HttpResponse response = httpclient.execute(httpPut);
        int code = response.getStatusLine().getStatusCode();
        if (code == HttpStatus.SC_OK) {
            String responseStr = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
            result = JSONObject.parseObject(responseStr, clazz);
        }
        return result;
    }


    /**
     * post请求
     *
     * @param url          请求地址
     * @param headerParams 请求头参数
     * @param requestBody  请求参数
     * @param clazz        返回对象类型
     */
    public <T> T doPostRequestIgnoreSSL(String url, Map<String, String> headerParams, String requestBody, Class<T> clazz)
            throws IOException, KeyManagementException, NoSuchAlgorithmException {

        //忽略证书
        X509TrustManager x509TrustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] arg0, String arg1) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] arg0, String arg1) {
                // 不验证
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        };

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[]{x509TrustManager}, new SecureRandom());
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);
        CloseableHttpClient httpclient = HttpClientBuilder.create().setSSLSocketFactory(sslSocketFactory).build();

        HttpPost httpPost = new HttpPost(url);
        T result = null;
        if (null != headerParams && !headerParams.isEmpty()) {
            for (Map.Entry<String, String> param : headerParams.entrySet()) {
                httpPost.addHeader(param.getKey(), param.getValue());
            }
        }
        if (null != requestBody) {
            StringEntity stringEntity = new StringEntity(requestBody, ContentType.APPLICATION_JSON);
            httpPost.setEntity(stringEntity);
        }
        HttpResponse response = httpclient.execute(httpPost);
        int code = response.getStatusLine().getStatusCode();
        if (code == HttpStatus.SC_OK) {
            String responseStr = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
            result = JSONObject.parseObject(responseStr, clazz);
        }
        return result;
    }

    public <T> T doPostRequestIgnoreSSL2(String url, Map<String, String> headerParams, String requestBody, Class<T> clazz) throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException, IOException {
        TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
        //忽略证书
        SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
                .loadTrustMaterial(null, acceptingTrustStrategy)
                .build();

        SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());

        CloseableHttpClient httpclient = HttpClients.custom()
                .setSSLSocketFactory(csf)
                .build();

        HttpPost httpPost = new HttpPost(url);
        T result = null;
        if (null != headerParams && !headerParams.isEmpty()) {
            for (Map.Entry<String, String> param : headerParams.entrySet()) {
                httpPost.addHeader(param.getKey(), param.getValue());
            }
        }
        if (null != requestBody) {
            StringEntity stringEntity = new StringEntity(requestBody, ContentType.APPLICATION_JSON);
            httpPost.setEntity(stringEntity);
        }
        HttpResponse response = httpclient.execute(httpPost);
        int code = response.getStatusLine().getStatusCode();
        if (code == HttpStatus.SC_OK) {
            String responseStr = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
            result = JSONObject.parseObject(responseStr, clazz);
        }
        return result;
    }
  
  /** 
    * @description: 文件传输
    * @date: 2024/4/12 11:48 
    * @param url 
    * @param multipartFiles 文件列表支持多个 
    * @param fileFiledName 目标接口接收文件的字段名 
    * @param params 其他参数 
    * @param headerParams 请求头参数 
    * @param timeout 超时时间(秒) 
    * @param clazz 
    * @return T 
    */ 
public <T> T doPostFileRequest(String url, List<MultipartFile> multipartFiles, String fileFiledName, Map<String, Object> params, Map<String, String> headerParams, int timeout, Class<T> clazz) throws IOException {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    T result = null;
    String responseStr = null;
  
    HttpPost httpPost = new HttpPost(url);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setCharset(java.nio.charset.Charset.forName("UTF-8"));
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
  
    String fileName = null;
    MultipartFile multipartFile = null;
    for (int i = 0; i < multipartFiles.size(); i++) {
        multipartFile = multipartFiles.get(i);
        fileName = multipartFile.getOriginalFilename(); 
       //文件流
        builder.addBinaryBody(fileFiledName, multipartFile.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);
    }
  
    if (null != headerParams && !headerParams.isEmpty()) {
        for (Map.Entry < String, String > param: headerParams.entrySet()) {
            httpPost.addHeader(param.getKey(), param.getValue());
        }
    } 
  
    //解决中文乱码
    if (null != params && !params.isEmpty()) {
        ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
        for (Map.Entry < String, Object > entry: params.entrySet()) {
            if (entry.getValue() == null) {
                continue;
            }
            //类似浏览器表单提交,对应input的name和value
            builder.addTextBody(entry.getKey(), entry.getValue().toString(), contentType);
        }
    }
  
    HttpEntity entity = builder.build();
    httpPost.setEntity(entity);
    HttpResponse response = httpClient.execute(httpPost); 
  
    //设置连接超时时间
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();
    httpPost.setConfig(requestConfig);
  
    int code = response.getStatusLine().getStatusCode();
    if (code == HttpStatus.SC_OK) {
        responseStr = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
        result = JSONObject.parseObject(responseStr, clazz);
    }
    return result;
 }
   
}

 

posted @ 2023-04-15 18:33  bug毁灭者  阅读(45)  评论(0编辑  收藏  举报