Skip to content

Commit

Permalink
feat: 提交okhttp【开启ssl验证】
Browse files Browse the repository at this point in the history
  • Loading branch information
KouShenhai committed Feb 1, 2025
1 parent bf31875 commit 87d6739
Show file tree
Hide file tree
Showing 9 changed files with 140 additions and 56 deletions.
5 changes: 5 additions & 0 deletions laokou-common/laokou-common-bom/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,11 @@
<!-- 定义全局jar版本,模块使用需要再次引入但不用写版本号 -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.freefair.okhttp-spring-boot</groupId>
<artifactId>okhttp4-spring-boot-starter</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<dependency>
<groupId>org.laokou</groupId>
<artifactId>laokou-logstash-client</artifactId>
Expand Down
4 changes: 4 additions & 0 deletions laokou-common/laokou-common-core/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,10 @@
<groupId>com.google.errorprone</groupId>
<artifactId>error_prone_annotations</artifactId>
</dependency>
<dependency>
<groupId>io.freefair.okhttp-spring-boot</groupId>
<artifactId>okhttp4-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.laokou</groupId>
<artifactId>laokou-common-test</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public class RestClientConfig {
public RestClient restClient() {
log.info("{} => Initializing Default RestClient", Thread.currentThread().getName());
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setHttpClient(getHttpClient(true));
factory.setHttpClient(getHttpClient());
return RestClient.builder().requestFactory(factory).build();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

package org.laokou.common.core.utils;

import jakarta.annotation.PreDestroy;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.hc.client5.http.classic.methods.HttpPost;
Expand All @@ -29,6 +30,7 @@
import org.apache.hc.client5.http.ssl.NoopHostnameVerifier;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.io.CloseMode;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
Expand All @@ -45,6 +47,8 @@
@Slf4j
public final class HttpUtil {

private static final CloseableHttpClient CLIENT = getHttpClient();

private HttpUtil() {
}

Expand All @@ -53,58 +57,49 @@ private HttpUtil() {
* @param url 链接
* @param params 参数
* @param headers 请求头
* @param disableSsl ssl开关
* @return 响应结果
*/
@SneakyThrows
public static String doFormDataPost(String url, Map<String, String> params, Map<String, String> headers,
boolean disableSsl) {
try (CloseableHttpClient httpClient = getHttpClient(disableSsl)) {
HttpPost httpPost = new HttpPost(url);
if (MapUtil.isNotEmpty(headers)) {
headers.forEach(httpPost::addHeader);
}
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
if (MapUtil.isNotEmpty(params)) {
params.forEach(entityBuilder::addTextBody);
}
HttpEntity httpEntity = entityBuilder.build();
httpPost.setEntity(httpEntity);
String resultString = EMPTY;
try {
// 执行请求
resultString = httpClient.execute(httpPost,
handler -> EntityUtils.toString(handler.getEntity(), StandardCharsets.UTF_8));
}
catch (IOException e) {
log.error("调用失败,错误信息:{}", e.getMessage());
}
return resultString;
public static String doFormDataPost(String url, Map<String, String> params, Map<String, String> headers) {
HttpPost httpPost = new HttpPost(url);
if (MapUtil.isNotEmpty(headers)) {
headers.forEach(httpPost::addHeader);
}
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
if (MapUtil.isNotEmpty(params)) {
params.forEach(entityBuilder::addTextBody);
}
HttpEntity httpEntity = entityBuilder.build();
httpPost.setEntity(httpEntity);
String resultString = EMPTY;
try {
// 执行请求
resultString = CLIENT.execute(httpPost,
handler -> EntityUtils.toString(handler.getEntity(), StandardCharsets.UTF_8));
}
catch (IOException e) {
log.error("调用失败,错误信息:{}", e.getMessage());
}
return resultString;
}

public static CloseableHttpClient getHttpClient(boolean disableSsl) {
public static CloseableHttpClient getHttpClient() {
// 创建HttpClient对象
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
if (disableSsl) {
disableSsl(httpClientBuilder);
}
return httpClientBuilder.build();
}

/**
* 关闭ssl校验.
* @param builder 构建器
*/
@SneakyThrows
private static void disableSsl(HttpClientBuilder builder) {
DefaultClientTlsStrategy tlsStrategy = new DefaultClientTlsStrategy(sslContext(),
NoopHostnameVerifier.INSTANCE);
PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = PoolingHttpClientConnectionManagerBuilder
.create()
.setTlsSocketStrategy(tlsStrategy)
.build();
builder.setConnectionManager(poolingHttpClientConnectionManager);
httpClientBuilder.setConnectionManager(poolingHttpClientConnectionManager);
return httpClientBuilder.build();
}

@PreDestroy
public void destroy() {
// 优雅停机
CLIENT.close(CloseMode.GRACEFUL);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/*
* Copyright (c) 2022-2025 KCloud-Platform-IoT Author or Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/

package org.laokou.common.core.utils;

import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.laokou.common.i18n.utils.ObjectUtil;
import org.laokou.common.i18n.utils.SslUtil;

import java.io.IOException;
import java.time.Duration;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static org.laokou.common.i18n.common.constant.StringConstant.EMPTY;

/**
* @author laokou
*/
@Slf4j
public final class OkHttpUtil {

private static final OkHttpClient CLIENT = getOkHttpClient();

private OkHttpUtil() {
}

public static String doFormDataPost(String url, Map<String, String> params, Map<String, String> headers) {
FormBody.Builder builder = new FormBody.Builder();
if (MapUtil.isNotEmpty(params)) {
params.forEach(builder::add);
}
Request request = new Request.Builder().url(url).headers(Headers.of(headers)).post(builder.build()).build();
try (Response response = CLIENT.newCall(request).execute()) {
ResponseBody body = response.body();
return ObjectUtil.isNotNull(body) ? body.string() : EMPTY;
}
catch (IOException e) {
log.error("调用失败,错误信息:{}", e.getMessage());
}
return EMPTY;
}

private static OkHttpClient getOkHttpClient() {
return new OkHttpClient.Builder()
.sslSocketFactory(SslUtil.sslContext().getSocketFactory(), SslUtil.DisableValidationTrustManager.INSTANCE)
.hostnameVerifier((hostname, session) -> true)
.connectTimeout(Duration.ofSeconds(10))
.readTimeout(Duration.ofSeconds(10))
.writeTimeout(Duration.ofSeconds(10))
.pingInterval(Duration.ZERO)
.connectionPool(new ConnectionPool(5, Duration.ofMinutes(5).toNanos(), TimeUnit.NANOSECONDS))
.build();
}

@PreDestroy
public void destroy() {
CLIENT.connectionPool().evictAll();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -50,14 +50,18 @@ public final class JacksonUtil {
/**
* 映射器配置.
*/
private static final ObjectMapper MAPPER = new ObjectMapper()
// 没有的属性不报错
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.registerModule(new JavaTimeModule());
private static final ObjectMapper MAPPER = getMapper();

private JacksonUtil() {
}

private static ObjectMapper getMapper() {
return new ObjectMapper()
// 没有的属性不报错
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.registerModule(new JavaTimeModule());
}

/**
* json字符转Bean.
* @param json json字符串
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,9 @@ public static void ignoreSSLTrust() {
HttpsURLConnection.setDefaultHostnameVerifier((hostname, sslSession) -> true);
}

private static class DisableValidationTrustManager implements X509TrustManager {
public static class DisableValidationTrustManager implements X509TrustManager {

public static final X509TrustManager INSTANCE = new DisableValidationTrustManager();

public DisableValidationTrustManager() {
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ public SmsResult send(String mobile) {
Map<String, String> params = Map.of("mobile", mobile, "param", paramValue, "smsSignId", signId, "templateId",
templateId);
String paramString = JacksonUtil.toJsonStr(Map.of("mobile", SensitiveUtil.formatMobile(mobile,3, 6), "content", TemplateUtil.getContent(TEMPLATES.get(templateId), param)));
String json = HttpUtil.doFormDataPost(URL, params, headers, true);
String json = HttpUtil.doFormDataPost(URL, params, headers);
JsonNode jsonNode = JacksonUtil.readTree(json);
int code = jsonNode.get("code").asInt();
if (code != SendStatus.OK.getCode()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,7 @@
import org.laokou.auth.dto.TokenRemoveCmd;
import org.laokou.auth.dto.clientobject.CaptchaCO;
import org.laokou.common.core.annotation.EnableTaskExecutor;
import org.laokou.common.core.utils.HttpUtil;
import org.laokou.common.core.utils.IdGenerator;
import org.laokou.common.core.utils.MDCUtil;
import org.laokou.common.core.utils.ThreadUtil;
import org.laokou.common.core.utils.*;
import org.laokou.common.crypto.utils.RSAUtil;
import org.laokou.common.i18n.utils.DateUtil;
import org.laokou.common.i18n.utils.JacksonUtil;
Expand Down Expand Up @@ -259,7 +256,7 @@ private Map<String, String> deviceAuthorizationCodeAuth(String deviceCode) {
"urn:ietf:params:oauth:grant-type:device_code");
Map<String, String> headers = Collections.singletonMap("Authorization",
"Basic OTVUeFNzVFBGQTN0RjEyVEJTTW1VVkswZGE6RnBId0lmdzR3WTkyZE8=");
String json = HttpUtil.doFormDataPost(apiUrl, params, headers, disabledSsl());
String json = HttpUtil.doFormDataPost(apiUrl, params, headers);
log.info("设备授权码认证模式,返回信息:{}", json);
String accessToken = JacksonUtil.readTree(json).get("access_token").asText();
String refreshToken = JacksonUtil.readTree(json).get("refresh_token").asText();
Expand All @@ -277,7 +274,7 @@ private Map<String, String> clientCredentialsAuth() {
Map<String, String> params = Map.of("grant_type", "client_credentials");
Map<String, String> headers = Collections.singletonMap("Authorization",
"Basic OTVUeFNzVFBGQTN0RjEyVEJTTW1VVkswZGE6RnBId0lmdzR3WTkyZE8=");
String json = HttpUtil.doFormDataPost(apiUrl, params, headers, disabledSsl());
String json = HttpUtil.doFormDataPost(apiUrl, params, headers);
log.info("客户端认证模式,返回信息:{}", json);
String accessToken = JacksonUtil.readTree(json).get("access_token").asText();
Assert.isTrue(StringUtil.isNotEmpty(accessToken), "access token is empty");
Expand All @@ -295,7 +292,7 @@ private Map<String, String> authorizationCodeAuth() {
"authorization_code");
Map<String, String> headers = Collections.singletonMap("Authorization",
"Basic OTVUeFNzVFBGQTN0RjEyVEJTTW1VVkswZGE6RnBId0lmdzR3WTkyZE8=");
String json = HttpUtil.doFormDataPost(apiUrl, params, headers, disabledSsl());
String json = HttpUtil.doFormDataPost(apiUrl, params, headers);
log.info("授权码认证模式,返回信息:{}", json);
String accessToken = JacksonUtil.readTree(json).get("access_token").asText();
String refreshToken = JacksonUtil.readTree(json).get("refresh_token").asText();
Expand All @@ -321,7 +318,7 @@ private Map<String, String> mobileAuth(String code) {
Map<String, String> headers = Map.of("Authorization",
"Basic OTVUeFNzVFBGQTN0RjEyVEJTTW1VVkswZGE6RnBId0lmdzR3WTkyZE8=", "User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 Edg/122.0.0.0");
String json = HttpUtil.doFormDataPost(apiUrl, params, headers, disabledSsl());
String json = HttpUtil.doFormDataPost(apiUrl, params, headers);
log.info("手机号认证,返回信息:{}", json);
String accessToken = JacksonUtil.readTree(json).get("access_token").asText();
String refreshToken = JacksonUtil.readTree(json).get("refresh_token").asText();
Expand All @@ -341,7 +338,7 @@ private Map<String, String> mailAuth(String code) {
Map<String, String> headers = Map.of("Authorization",
"Basic OTVUeFNzVFBGQTN0RjEyVEJTTW1VVkswZGE6RnBId0lmdzR3WTkyZE8=", "User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 Edg/122.0.0.0");
String json = HttpUtil.doFormDataPost(apiUrl, params, headers, disabledSsl());
String json = HttpUtil.doFormDataPost(apiUrl, params, headers);
log.info("邮箱认证,返回信息:{}", json);
String accessToken = JacksonUtil.readTree(json).get("access_token").asText();
String refreshToken = JacksonUtil.readTree(json).get("refresh_token").asText();
Expand All @@ -363,7 +360,7 @@ private Map<String, String> usernamePasswordAuth(String captcha, String username
"Basic OTVUeFNzVFBGQTN0RjEyVEJTTW1VVkswZGE6RnBId0lmdzR3WTkyZE8=", "trace-id",
String.valueOf(IdGenerator.defaultSnowflakeId()), "User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 Edg/122.0.0.0");
String json = HttpUtil.doFormDataPost(apiUrl, params, headers, disabledSsl());
String json = OkHttpUtil.doFormDataPost(apiUrl, params, headers);
log.info("用户名密码认证模式,返回信息:{}", json);
String accessToken = JacksonUtil.readTree(json).get("access_token").asText();
String refreshToken = JacksonUtil.readTree(json).get("refresh_token").asText();
Expand All @@ -381,7 +378,7 @@ private String getRefreshToken(String refreshToken) {
Map<String, String> params = Map.of("refresh_token", refreshToken, "grant_type", "refresh_token");
Map<String, String> headers = Collections.singletonMap("Authorization",
"Basic OTVUeFNzVFBGQTN0RjEyVEJTTW1VVkswZGE6RnBId0lmdzR3WTkyZE8=");
String json = HttpUtil.doFormDataPost(apiUrl, params, headers, disabledSsl());
String json = HttpUtil.doFormDataPost(apiUrl, params, headers);
log.info("刷新令牌模式,返回信息;{}", json);
return JacksonUtil.readTree(json).get("access_token").asText();
}
Expand Down

0 comments on commit 87d6739

Please sign in to comment.