首页 > 编程语言 >JAVA远程请求工具类

JAVA远程请求工具类

时间:2023-04-15 18:59:15浏览次数:42  
标签:JAVA 请求 headerParams param org apache import new 远程

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;
    }
}

 

标签:JAVA,请求,headerParams,param,org,apache,import,new,远程
From: https://www.cnblogs.com/guliang/p/17271546.html

相关文章

  • Java笔记(16) Collection集合-->Set集合-->HashSet
    1.Set接口基本介绍Set是无序集合(添加和取出的顺序不一致,但取出的顺序是固定的),没有索引不允许重复元素,所以最多包含一个nullJDKAPI中Set接口的实现类有:Abstract,ConcurrentHashMap.KeySetView,ConcurrentSkipListSet,CopyOnWriteArraySet,EnumSet,HashSet,JobStateRea......
  • Python3基本请求库-urllib
    urlliburlopen一个基本请求fromurllibimportrequest,parsedefApi():#禁用证书验证ssl._create_default_https_context=ssl._create_unverified_contextresponse=request.urlopen('https://www.baidu.com/')print(response.read().decode(�......
  • java的协变和逆变
    一、协变和逆变的概念协变:模板中赋值给A的是A或者A的子类。比如:List<?extendsA>listA=List<ChildA>()即:ChildA可能是A或者A的子类逆变:模板中赋值给A的是A或者A的父类。比如:List<?superA>listA=List<ParentA>()即: ParentA可能是A或者A的父类二、为何会有协变和逆......
  • java maven-plugin-shade插件 Maven生成的jar运行出现“没有主清单属性”
    命令窗口运行jar,提示“没有主清单属性”  2.1分析问题在打包构建的jar目录内,可以看到有一个MANIFEST.MF文件,如图所示:该文件就是jar运行时要查找的清单目录,其中主清单数据,就是我们要运行的主类(函数入口main所在的类);提示缺少主清单属性,就是文件中少了主清单属性如下所示:正......
  • java——微服务——spring cloud——前言导读
                       黑马课程连接:https://www.bilibili.com/video/BV1LQ4y127n4?p=1&vd_source=79bbd5b76bfd74c2ef1501653cee29d6 ......
  • java——maven——分模块——资源加载属性值
    第一步:   第二步:    第三步:                       ......
  • java——maven——分模块——属性定义与使用
                   版本号统一管理                 ......
  • java——maven——分模块——模块继承
    通过父工程,管理所有子模块的依赖版本管理    把所有依赖放入dependentmanagement下面        所有的子工程需要修改,引入父工程,然后子工程里面的引入依赖的版本号全部去除,交由父工程统一管理:       插件依赖,也可以进行版本统一管理:......
  • java: 无法访问org.springframework.boot.SpringApplication
    在运行springboot项目中的Application.java时出现:错误的类文件: /D:/install/Maven/apache-maven-3.6.1/repository/org/springframework/boot/spring-boot/3.0.5/spring-boot-3.0.5.jar!/org/springframework/boot/SpringApplication.class   类文件具有错误的版本 61.0, ......
  • JavaScript 邮箱 验证正则表达式 ,包看懂
    \w就是[0-9a-zA-Z_]\s是[\t\v\n\r\f]\S是[^\t\v\n\r\f]\W是[^0-9a-zA-Z_]\D就是[^0-9]\d就是[0-9].就是[^\n\r\u2028\u2029]。表示几乎任意字符。varreg=/\w{1,30}(\.\w{1,10}){0,2}@\w{1,10}\.\w{1,10}/g\w{1,30}理解为至少有一个字符,最多30个.\w{1,30}理......