当前位置: 首页 > news >正文

java实现http/https请求

在Java中,有多种方式可以实现HTTP或HTTPS请求。以下是使用第三方库Apache HttpClient来实现HTTP/HTTPS请求的工具类。

优势和特点

URIBuilder的优势在于它提供了一种简单而灵活的方式来构造URI,帮助开发人员避免手动拼接URI字符串,并处理参数的编码和转义。此外,URIBuilder还提供了其他一些有用的方法,例如添加路径段、设置查询字符串等。这使得URI的构建过程更加清晰和易于管理。

使用 Apache HttpClient

要使用Apache HttpClient,你首先需要将HttpClient库添加到你的项目中。如果你使用Maven,可以在pom.xml中添加以下依赖:

<dependency> 

    <groupId>org.apache.httpcomponents</groupId> 

    <artifactId>httpclient</artifactId> 

    <version>4.5.13</version> <!-- 使用时请检查最新版本 --> 

</dependency>

然后,你可以使用以下代码示例来发送HTTP请求:

import org.apache.commons.collections.MapUtils;

import org.apache.http.HttpEntity;

import org.apache.http.client.methods.CloseableHttpResponse;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.client.utils.URIBuilder;

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.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClients;

import org.apache.http.ssl.SSLContextBuilder;

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.IOException;

import java.security.KeyManagementException;

import java.security.KeyStoreException;

import java.security.NoSuchAlgorithmException;

import java.security.cert.CertificateException;

import java.security.cert.X509Certificate;

import java.util.HashMap;

import java.util.Map;

public class HttpsUtils {

    private static Logger logger = LoggerFactory.getLogger(HttpsUtils.class);

    static CloseableHttpClient httpClient;

    static CloseableHttpResponse httpResponse;

    public static CloseableHttpClient createSSLClientDefault() {

        try {

            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

                // 信任所有

                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {

                    return true;

                }

            }).build();

            HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;

            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);

            return HttpClients.custom().setSSLSocketFactory(sslsf).build();

        } catch (KeyManagementException e) {

            e.printStackTrace();

        } catch (NoSuchAlgorithmException e) {

            e.printStackTrace();

        } catch (KeyStoreException e) {

            e.printStackTrace();

        }

        return HttpClients.createDefault();

    }

    /**

    * 发送https||http get请求

    *

    * @throws Exception

    */

    public static String sendByHttpGet(Map<String, Object> params, String url) {

        try {

            URIBuilder uriBuilder = new URIBuilder(url);

            if(MapUtils.isNotEmpty(params)) {

                for (Map.Entry<String, Object> entry : params.entrySet()) {

                    uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());

                }

            }

            HttpGet httpGet = new HttpGet(uriBuilder.build());

            httpGet.addHeader("Content-type", "application/json; charset=utf-8");

            httpGet.setHeader("Accept", "application/json");

            httpClient = HttpsUtils.createSSLClientDefault();

            httpResponse = httpClient.execute(httpGet);

            HttpEntity httpEntity = httpResponse.getEntity();

            if (httpEntity != null) {

                String jsObject = EntityUtils.toString(httpEntity, "UTF-8");

                return jsObject;

            } else {

                return null;

            }

        } catch (Exception e) {

            e.printStackTrace();

            logger.error("description : {{}} ,details : {{}}", "请求异常", e.getStackTrace());

        } finally {

            try {

                httpResponse.close();

                httpClient.close();

            } catch (IOException e) {

                logger.error("description : {{}} ,details : {{}}", "请求流关闭异常", e.getStackTrace());

                e.printStackTrace();

            }

        }

        return null;

    }

    /**

    * 发送https||http get请求

    *

    * @throws Exception

    */

    public static byte[] sendByteByHttpGet(Map<String, Object> params, String url) {

        try {

            URIBuilder uriBuilder = new URIBuilder(url);

            if(MapUtils.isNotEmpty(params)) {

                for (Map.Entry<String, Object> entry : params.entrySet()) {

                    uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());

                }

            }

            HttpGet httpGet = new HttpGet(uriBuilder.build());

            httpGet.addHeader("Content-type", "application/json; charset=utf-8");

            httpGet.setHeader("Accept", "application/json");

            httpClient = HttpsUtils.createSSLClientDefault();

            httpResponse = httpClient.execute(httpGet);

            HttpEntity httpEntity = httpResponse.getEntity();

            if (httpEntity != null) {

                byte[] bytes = EntityUtils.toByteArray(httpEntity);

                return bytes;

            } else {

                return new byte[0];

            }

        } catch (Exception e) {

            e.printStackTrace();

            logger.error("description : {{}} ,details : {{}}", "读取二进制保存的图片异常", e.getStackTrace());

        } finally {

            try {

                httpResponse.close();

                httpClient.close();

            } catch (IOException e) {

                e.printStackTrace();

                logger.error("description : {{}} ,details : {{}}", "读取二进制保存的图片关闭流时异常", e.getStackTrace());

            }

        }

        return new byte[0];

    }

}

http://www.lryc.cn/news/388692.html

相关文章:

  • NC204871 求和
  • git克隆代码warning: could not find UI helper ‘git-credential-manager-ui‘
  • Generator 是怎么样使用的以及各个阶段的变化如何
  • 一文了解Java中 Vector、ArrayList、LinkedList 之间的区别
  • 【论文复现|智能算法改进】基于自适应动态鲸鱼优化算法的路径规划研究
  • 【Win测试】窗口捕获的学习笔记
  • PostgreSQL的学习心得和知识总结(一百四十七)|深入理解PostgreSQL数据库之transaction chain的使用和实现
  • 宝塔linux网站迁移步骤
  • 电路笔记(三极管器件): MOSFETIGBT
  • Docker 镜像导出和导入
  • QueryClientProvider is not defined
  • HTTPS是什么?原理是什么?用公钥加密为什么不能用公钥解密?
  • 系统中非功能性需求的思考
  • 力扣第215题“数组中的第K个最大元素”
  • java.util.function实现原理和Java使用场景【Function、Predicate集合转换过滤,BiConsumer事件处理】
  • 《每天5分钟用Flask搭建一个管理系统》 第6章:数据库集成
  • pandas读取和处理Excel文件的基础应用1
  • electron vite react 创建一个项目
  • 鸿蒙使用 @Builder扩展出来的布局数据更新没法更新UI
  • 湖南省教育网络协会莅临麒麟信安调研教育网络数字化建设及教育信创发展情况
  • 论文阅读_优化RAG系统的检索
  • STC8/32 软硬件I2C通讯方式扫描I2C设备地址
  • Linux——数据流和重定向,制作镜像
  • Windows 11的市场份额越来越大了,推荐你升级!
  • 微服务架构中的调试难题与分布式事务解决方案
  • 银行家算法-操作系统中避免死锁的最著名算法
  • PCL 基于点云RGB颜色的区域生长算法
  • cube-studio开源一站式机器学习平台,在线ide,jupyter,vscode,matlab,rstudio,ssh远程连接,tensorboard
  • 1976 ssm 营地管理系统开发mysql数据库web结构java编程计算机网页源码Myeclipse项目
  • 技术派全局异常处理