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

}

}

相关推荐
奇遇少年几秒前
HTTPS基础
网络协议·http·https
德迅云安全--陈琦琦几秒前
详解 HTTP 中间人攻击
网络协议·http·iphone
AskHarries7 分钟前
Spring Boot集成geode快速入门Demo
java·spring boot·后端·geode
小哇66619 分钟前
SpringBoot整合Minio
java·spring boot·spring
Tech Synapse33 分钟前
Java循环创建对象内存溢出怎么解决
java·开发语言·jvm
IT·陈寒33 分钟前
Kotlin vs Java:深入解析两者之间的最新差异与优劣(全面指南)
java·python·kotlin
行动π技术博客44 分钟前
spring中IOC相关介绍
java·spring·rpc
吃青椒的小新1 小时前
独一无二的设计模式——单例模式(Java实现)
java·后端·单例模式·设计模式
天才梦浪1 小时前
开源租房项目
java·项目
才艺のblog1 小时前
127还是localhost....?
javascript·https·浏览器特性