perf:移除hutool的http模块,使用okhttp3
This commit is contained in:
@@ -14,6 +14,8 @@ import com.tiesheng.demo.pojos.PoiBean;
|
||||
import com.tiesheng.demo.pojos.TestFile;
|
||||
import com.tiesheng.message.pojos.MessageReqResp;
|
||||
import com.tiesheng.message.pojos.UserChannel;
|
||||
import com.tiesheng.platform.config.ding.PlatformDingConfig;
|
||||
import com.tiesheng.platform.config.ding.bean.DingUserInfo;
|
||||
import com.tiesheng.util.config.EncryptConfig;
|
||||
import com.tiesheng.util.config.GlobalConfig;
|
||||
import com.tiesheng.util.config.Ip2regionConfig;
|
||||
@@ -26,6 +28,7 @@ import com.tiesheng.web.service.CoreMessageService;
|
||||
import com.tiesheng.web.util.ProcessImportConsumer;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@@ -33,6 +36,7 @@ import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* @author hao
|
||||
@@ -57,6 +61,8 @@ public class TestController {
|
||||
DbBackupConfig dbBackupConfig;
|
||||
@Autowired
|
||||
TsCacheService tsCacheService;
|
||||
@Autowired
|
||||
PlatformDingConfig platformDingConfig;
|
||||
|
||||
|
||||
@RequestMapping("/index")
|
||||
@@ -108,8 +114,14 @@ public class TestController {
|
||||
public ApiResp<String> export() {
|
||||
|
||||
// tsCacheService.put("fdfhdfd", "fdfdfdfd");
|
||||
String s = tsCacheService.get("fdfhdfd");
|
||||
LogFactory.get().info("export: " + s);
|
||||
// String s = tsCacheService.get("fdfhdfd");
|
||||
// LogFactory.get().info("export: " + s);
|
||||
|
||||
platformDingConfig.syncDeptUser("", null, new Consumer<DingUserInfo>() {
|
||||
@Override
|
||||
public void accept(DingUserInfo dingUserInfo) {
|
||||
}
|
||||
});
|
||||
|
||||
// List<TestFile> list = new ArrayList<>();
|
||||
// list.add(new TestFile("11111"));
|
||||
@@ -131,14 +143,13 @@ public class TestController {
|
||||
}
|
||||
|
||||
|
||||
@RequestMapping("searchIP")
|
||||
@PostMapping("searchIP")
|
||||
@TokenIgnore
|
||||
public ApiResp<String> searchIp() {
|
||||
String search = ip2regionConfig.search("127.0.0.1");
|
||||
return ApiResp.respOK(search);
|
||||
}
|
||||
|
||||
|
||||
@RequestMapping("desensitize")
|
||||
@TokenIgnore
|
||||
public ApiResp<List<TestFile>> desensitize() {
|
||||
|
||||
@@ -4,7 +4,7 @@ import cn.hutool.core.date.DateUtil;
|
||||
import cn.hutool.json.JSONObject;
|
||||
import cn.hutool.json.JSONUtil;
|
||||
import com.tiesheng.message.config.aliyun.AliyunSmsHandler;
|
||||
import com.tiesheng.message.pojos.AliyunTempParam;
|
||||
import com.tiesheng.message.config.aliyun.AliyunTempParam;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
@@ -11,6 +11,12 @@ spring:
|
||||
url: redis://kyF0zUL3011111@47.96.30.85:6234
|
||||
|
||||
platform:
|
||||
ding:
|
||||
global:
|
||||
corpId: dingebe664cb3baf3a52a39a90f97fcb1e09
|
||||
agentId: 2474444028
|
||||
appKey: dingyvf1niiajfaajyo5
|
||||
appSecret: y6SGZ4fvPbdbj4RVbDWLeMBkGgplaOdnTA_9wN5TDdOV_Y47alYc1LDlIHjsBJE1
|
||||
wxmp:
|
||||
global:
|
||||
app-id: wxa0343fe519824651
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package com.tiesheng.message.config.aliyun;
|
||||
|
||||
import cn.hutool.json.JSONObject;
|
||||
import com.tiesheng.message.pojos.AliyunTempParam;
|
||||
|
||||
public interface AliyunSmsHandler {
|
||||
|
||||
|
||||
@@ -5,13 +5,12 @@ import cn.hutool.core.lang.Validator;
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import cn.hutool.crypto.SecureUtil;
|
||||
import cn.hutool.http.HttpUtil;
|
||||
import cn.hutool.json.JSONObject;
|
||||
import cn.hutool.json.JSONUtil;
|
||||
import com.tiesheng.message.pojos.AliyunTempParam;
|
||||
import com.tiesheng.message.pojos.MessageReqResp;
|
||||
import com.tiesheng.message.service.TieshengMessageSender;
|
||||
import com.tiesheng.util.exception.ApiException;
|
||||
import com.tiesheng.util.service.http.OkHttpUtil;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
@@ -102,7 +101,7 @@ public class AliyunSmsSender implements TieshengMessageSender {
|
||||
|
||||
String respBody = "";
|
||||
try {
|
||||
respBody = HttpUtil.get(ENDPOINT + "?Signature=" + signature + sortQueryStringTmp, 10 * 1000);
|
||||
respBody = OkHttpUtil.get(ENDPOINT + "?Signature=" + signature + sortQueryStringTmp);
|
||||
} catch (Exception e) {
|
||||
respBody = JSONUtil.createObj()
|
||||
.putOpt("Code", "Error")
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.tiesheng.message.pojos;
|
||||
package com.tiesheng.message.config.aliyun;
|
||||
|
||||
import cn.hutool.json.JSONObject;
|
||||
|
||||
@@ -4,18 +4,18 @@ import cn.hutool.core.collection.CollUtil;
|
||||
import cn.hutool.core.lang.TypeReference;
|
||||
import cn.hutool.core.map.MapUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import cn.hutool.http.HttpRequest;
|
||||
import cn.hutool.http.HttpResponse;
|
||||
import cn.hutool.http.HttpUtil;
|
||||
import cn.hutool.json.JSONObject;
|
||||
import cn.hutool.json.JSONUtil;
|
||||
import cn.hutool.log.LogFactory;
|
||||
import com.tiesheng.platform.config.ding.bean.*;
|
||||
import com.tiesheng.util.exception.ApiException;
|
||||
import com.tiesheng.util.service.TsCacheService;
|
||||
import com.tiesheng.util.service.http.OkHttpUtil;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.Response;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
@@ -69,26 +69,25 @@ public class PlatformDingConfig {
|
||||
url = url + "?access_token=" + accessToken;
|
||||
}
|
||||
|
||||
HttpRequest request;
|
||||
Request request;
|
||||
if (body == null) {
|
||||
request = HttpUtil.createGet(url);
|
||||
request = OkHttpUtil.ofGet(url);
|
||||
} else {
|
||||
request = HttpUtil.createPost(url).body(body.toString());
|
||||
request = OkHttpUtil.ofPost(url, body);
|
||||
}
|
||||
request.header("x-acs-dingtalk-access-token", accessToken);
|
||||
HttpResponse execute = request.execute();
|
||||
|
||||
if (execute.isOk()) {
|
||||
String rawBody = execute.body();
|
||||
DingResponse<T> bean = JSONUtil.toBean(rawBody, typeReference, true);
|
||||
if (!bean.isOk()) {
|
||||
LogFactory.get().info(bean.getErrmsg());
|
||||
request.newBuilder().header("x-acs-dingtalk-access-token", accessToken);
|
||||
try {
|
||||
Response response = OkHttpUtil.ofHttpClient().build().newCall(request).execute();
|
||||
if (response.isSuccessful() || response.body() != null) {
|
||||
String rawBody = response.body().string();
|
||||
DingResponse<T> bean = JSONUtil.toBean(rawBody, typeReference, true);
|
||||
bean.setRawBody(rawBody);
|
||||
return bean;
|
||||
}
|
||||
bean.setRawBody(rawBody);
|
||||
return bean;
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
|
||||
return null;
|
||||
return DingResponse.ofError();
|
||||
}
|
||||
|
||||
|
||||
@@ -113,7 +112,7 @@ public class PlatformDingConfig {
|
||||
Map<String, Object> query = new HashMap<>(10);
|
||||
query.put("appkey", dingConfigBean.getAppKey());
|
||||
query.put("appsecret", dingConfigBean.getAppSecret());
|
||||
String response = HttpUtil.get("https://oapi.dingtalk.com/gettoken", query);
|
||||
String response = OkHttpUtil.get("https://oapi.dingtalk.com/gettoken", query);
|
||||
JSONObject respJson = JSONUtil.parseObj(response);
|
||||
accessToken = respJson.getStr("access_token");
|
||||
TsCacheService.of().put(CACHE_ACCESS_TOKEN + dingConfigBean.getAppKey(),
|
||||
|
||||
@@ -21,6 +21,19 @@ public class DingResponse<T> {
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 构造一个异常对象
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public static <T> DingResponse<T> ofError() {
|
||||
DingResponse<T> response = new DingResponse<>();
|
||||
response.setErrcode("-1");
|
||||
response.setErrmsg("网络访问异常。");
|
||||
return response;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 从原始数据中获取值
|
||||
*
|
||||
|
||||
@@ -2,12 +2,11 @@ package com.tiesheng.platform.config.wxmini;
|
||||
|
||||
|
||||
import cn.hutool.core.map.MapUtil;
|
||||
import cn.hutool.http.HttpRequest;
|
||||
import cn.hutool.http.HttpResponse;
|
||||
import cn.hutool.json.JSONObject;
|
||||
import cn.hutool.json.JSONUtil;
|
||||
import com.tiesheng.platform.config.wxmp.bean.WxConfigBean;
|
||||
import com.tiesheng.util.exception.ApiException;
|
||||
import com.tiesheng.util.service.http.OkHttpUtil;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@@ -51,13 +50,14 @@ public class PlatformWxminiConfig {
|
||||
*/
|
||||
public String jscode2session(String service, String code) {
|
||||
WxConfigBean configBean = getConfigBean(service);
|
||||
try (HttpResponse response = HttpRequest.get("https://api.weixin.qq.com/sns/jscode2session"
|
||||
|
||||
String body = OkHttpUtil.get("https://api.weixin.qq.com/sns/jscode2session"
|
||||
+ "?appid=" + configBean.getAppId()
|
||||
+ "&secret=" + configBean.getAppSecret()
|
||||
+ "&js_code=" + code + "&grant_type=authorization_code").execute()) {
|
||||
JSONObject object = JSONUtil.parseObj(response.body());
|
||||
return object.getStr("openid");
|
||||
}
|
||||
+ "&js_code=" + code + "&grant_type=authorization_code");
|
||||
|
||||
JSONObject object = JSONUtil.parseObj(body);
|
||||
return object.getStr("openid");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -67,12 +67,13 @@ public class PlatformWxminiConfig {
|
||||
*/
|
||||
public String getAccessToken(String service) {
|
||||
WxConfigBean configBean = getConfigBean(service);
|
||||
try (HttpResponse response = HttpRequest.get("https://api.weixin.qq.com/cgi-bin/token"
|
||||
|
||||
String body = OkHttpUtil.get("https://api.weixin.qq.com/cgi-bin/token"
|
||||
+ "?grant_type=client_credential&appid=" + configBean.getAppId()
|
||||
+ "&secret=" + configBean.getAppSecret()).execute()) {
|
||||
JSONObject object = JSONUtil.parseObj(response.body());
|
||||
return object.getStr("access_token");
|
||||
}
|
||||
+ "&secret=" + configBean.getAppSecret());
|
||||
|
||||
JSONObject object = JSONUtil.parseObj(body);
|
||||
return object.getStr("access_token");
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,6 @@ package com.tiesheng.platform.config.wxmp;
|
||||
import cn.hutool.core.map.MapUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import cn.hutool.core.util.URLUtil;
|
||||
import cn.hutool.http.HttpUtil;
|
||||
import cn.hutool.json.JSONObject;
|
||||
import cn.hutool.json.JSONUtil;
|
||||
import cn.hutool.log.LogFactory;
|
||||
@@ -14,6 +13,7 @@ import com.tiesheng.platform.config.wxmp.bean.WxOAuth2AccessToken;
|
||||
import com.tiesheng.platform.config.wxmp.bean.WxUserInfo;
|
||||
import com.tiesheng.util.exception.ApiException;
|
||||
import com.tiesheng.util.service.TsCacheService;
|
||||
import com.tiesheng.util.service.http.OkHttpUtil;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@@ -69,7 +69,7 @@ public class PlatformWxmpConfig {
|
||||
query.put("grant_type", "client_credential");
|
||||
query.put("appid", configBean.getAppId());
|
||||
query.put("secret", configBean.getAppSecret());
|
||||
String response = HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token", query);
|
||||
String response = OkHttpUtil.get("https://api.weixin.qq.com/cgi-bin/token", query);
|
||||
JSONObject respJson = JSONUtil.parseObj(response);
|
||||
accessToken = respJson.getStr("access_token");
|
||||
TsCacheService.of().put(CACHE_ACCESS_TOKEN + configBean.getAppId(), accessToken,
|
||||
@@ -91,7 +91,7 @@ public class PlatformWxmpConfig {
|
||||
Map<String, Object> query = new HashMap<>(10);
|
||||
query.put("access_token", getAccessToken(service));
|
||||
query.put("type", "jsapi");
|
||||
String response = HttpUtil.get("https://api.weixin.qq.com/cgi-bin/ticket/getticket", query);
|
||||
String response = OkHttpUtil.get("https://api.weixin.qq.com/cgi-bin/ticket/getticket", query);
|
||||
LogFactory.get().info("getJsapiTicket: " + response);
|
||||
JSONObject respJson = JSONUtil.parseObj(response);
|
||||
jsapiTicket = respJson.getStr("ticket");
|
||||
@@ -156,7 +156,7 @@ public class PlatformWxmpConfig {
|
||||
public void mediaPicGet(String service, String mediaId, String filePath) {
|
||||
String fileUrl = String.format("https://api.weixin.qq.com/cgi-bin/media/get?access_token=%s&media_id=%s",
|
||||
getAccessToken(service), mediaId);
|
||||
HttpUtil.downloadFile(fileUrl, filePath);
|
||||
OkHttpUtil.downloadFile(fileUrl, filePath);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
package com.tiesheng.platform.config.wxmp.bean;
|
||||
|
||||
import cn.hutool.http.HttpUtil;
|
||||
import cn.hutool.json.JSONObject;
|
||||
import cn.hutool.json.JSONUtil;
|
||||
import com.tiesheng.util.service.http.OkHttpUtil;
|
||||
|
||||
/**
|
||||
* @author hao
|
||||
@@ -13,7 +13,7 @@ public class WxOAuth2AccessToken {
|
||||
private String openid;
|
||||
|
||||
public static WxOAuth2AccessToken create(String appId, String secret, String code) {
|
||||
String response = HttpUtil.get("https://api.weixin.qq.com/sns/oauth2/access_token" +
|
||||
String response = OkHttpUtil.get("https://api.weixin.qq.com/sns/oauth2/access_token" +
|
||||
"?appid=" + appId + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code");
|
||||
JSONObject respJson = JSONUtil.parseObj(response);
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package com.tiesheng.platform.config.wxmp.bean;
|
||||
|
||||
import cn.hutool.http.HttpUtil;
|
||||
import cn.hutool.json.JSONUtil;
|
||||
import com.tiesheng.util.service.http.OkHttpUtil;
|
||||
|
||||
/**
|
||||
* @author hao
|
||||
@@ -30,7 +30,7 @@ public class WxUserInfo {
|
||||
* @return
|
||||
*/
|
||||
public static WxUserInfo create(WxOAuth2AccessToken oAuth2AccessToken) {
|
||||
String s = HttpUtil.get("https://api.weixin.qq.com/sns/userinfo"
|
||||
String s = OkHttpUtil.get("https://api.weixin.qq.com/sns/userinfo"
|
||||
+ "?access_token=" + oAuth2AccessToken.getAccessToken()
|
||||
+ "&openid=" + oAuth2AccessToken.getOpenid() + "&lang=zh_CN");
|
||||
return JSONUtil.toBean(s, WxUserInfo.class);
|
||||
|
||||
@@ -32,8 +32,21 @@
|
||||
|
||||
<dependency>
|
||||
<groupId>cn.hutool</groupId>
|
||||
<artifactId>hutool-all</artifactId>
|
||||
<artifactId>hutool-bom</artifactId>
|
||||
<version>5.8.16</version>
|
||||
<type>pom</type>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>cn.hutool</groupId>
|
||||
<artifactId>hutool-http</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.squareup.okhttp3</groupId>
|
||||
<artifactId>okhttp</artifactId>
|
||||
<version>4.12.0</version>
|
||||
</dependency>
|
||||
|
||||
<!-- MySql驱动 -->
|
||||
|
||||
@@ -4,9 +4,7 @@ import cn.hutool.core.collection.CollUtil;
|
||||
import cn.hutool.core.comparator.VersionComparator;
|
||||
import cn.hutool.core.io.FileUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import cn.hutool.core.util.URLUtil;
|
||||
import cn.hutool.extra.spring.SpringUtil;
|
||||
import cn.hutool.http.HttpGlobalConfig;
|
||||
import cn.hutool.log.LogFactory;
|
||||
import com.tiesheng.util.exception.ApiException;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
@@ -14,7 +12,6 @@ import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
@@ -40,14 +37,6 @@ public class GlobalConfig {
|
||||
private HashMap<String, String> ext;
|
||||
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
// 默认10s的超时时间
|
||||
HttpGlobalConfig.setTimeout(10 * 1000);
|
||||
// 最多重定向3次
|
||||
HttpGlobalConfig.setMaxRedirectCount(3);
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// 逻辑方法
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
package com.tiesheng.util.config;
|
||||
|
||||
import cn.hutool.core.io.FileUtil;
|
||||
import cn.hutool.http.HttpUtil;
|
||||
import cn.hutool.log.LogFactory;
|
||||
import com.tiesheng.util.ip2region.Searcher;
|
||||
import com.tiesheng.util.service.http.OkHttpUtil;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@@ -27,7 +27,7 @@ public class Ip2regionConfig {
|
||||
public void downloadDbFile() {
|
||||
if (!FileUtil.exist(dbPath)) {
|
||||
LogFactory.get().info("download ip2region file start");
|
||||
HttpUtil.downloadFile(dbUrl, dbPath);
|
||||
OkHttpUtil.downloadFile(dbUrl, dbPath);
|
||||
LogFactory.get().info("download ip2region file finish");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,8 +6,8 @@ import cn.hutool.core.util.CharUtil;
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import cn.hutool.extra.spring.SpringUtil;
|
||||
import cn.hutool.http.HttpUtil;
|
||||
import com.tiesheng.util.config.GlobalConfig;
|
||||
import com.tiesheng.util.service.http.OkHttpUtil;
|
||||
|
||||
public class FileUploadPath {
|
||||
|
||||
@@ -71,7 +71,7 @@ public class FileUploadPath {
|
||||
String newFileName = UPLOAD_FOLDER + StrUtil.subAfter(httpUrl, UPLOAD_FOLDER, true);
|
||||
FileUploadPath uploadPath = file(newFileName);
|
||||
if (!FileUtil.exist(uploadPath.getAbsolutePath())) {
|
||||
HttpUtil.downloadFile(httpUrl, uploadPath.getAbsolutePath());
|
||||
OkHttpUtil.downloadFile(httpUrl, uploadPath.getAbsolutePath());
|
||||
}
|
||||
|
||||
return uploadPath.getHttpPath();
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.tiesheng.util.service.http;
|
||||
|
||||
import cn.hutool.json.JSONUtil;
|
||||
import cn.hutool.log.LogFactory;
|
||||
import okhttp3.Interceptor;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.Response;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public class HttpLogInterceptor implements Interceptor {
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public Response intercept(@NotNull Chain chain) {
|
||||
|
||||
Request request = chain.request();
|
||||
|
||||
Response response;
|
||||
try {
|
||||
response = chain.proceed(request);
|
||||
} catch (Exception e) {
|
||||
response = new Response.Builder()
|
||||
.request(request)
|
||||
.body(OkHttpUtil.ofJsonResponse(JSONUtil.createObj()
|
||||
.putOpt("code", -1)
|
||||
.putOpt("message", e.getMessage())
|
||||
.putOpt("exception", e)
|
||||
.toString()))
|
||||
.code(200).build();
|
||||
}
|
||||
|
||||
LogFactory.get().info("url: {},body: {}", request.url(), response.body().contentType().toString());
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.tiesheng.util.service.http;
|
||||
|
||||
import okhttp3.Interceptor;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationListener;
|
||||
import org.springframework.context.event.ContextRefreshedEvent;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Component
|
||||
public class OkHttpConfig implements ApplicationListener<ContextRefreshedEvent> {
|
||||
|
||||
|
||||
/**
|
||||
* 全局连接超时
|
||||
*/
|
||||
public static int GLOBAL_TIMEOUT = 5 * 1000;
|
||||
|
||||
|
||||
/**
|
||||
* 全局拦截器
|
||||
*/
|
||||
public static final List<Interceptor> INTERCEPTORS = new ArrayList<>();
|
||||
|
||||
|
||||
@Override
|
||||
public void onApplicationEvent(ContextRefreshedEvent event) {
|
||||
ApplicationContext applicationContext = event.getApplicationContext();
|
||||
Map<String, Interceptor> beansOfType = applicationContext.getBeansOfType(Interceptor.class);
|
||||
for (Map.Entry<String, Interceptor> entry : beansOfType.entrySet()) {
|
||||
INTERCEPTORS.add(entry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// setter、getter
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* 设置全局超时时间
|
||||
*
|
||||
* @param timeout
|
||||
*/
|
||||
public static void setGlobalTimeout(int timeout) {
|
||||
GLOBAL_TIMEOUT = timeout;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
package com.tiesheng.util.service.http;
|
||||
|
||||
import cn.hutool.core.io.FileUtil;
|
||||
import cn.hutool.core.net.url.UrlQuery;
|
||||
import cn.hutool.core.util.CharsetUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import cn.hutool.json.JSONObject;
|
||||
import okhttp3.*;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class OkHttpUtil {
|
||||
|
||||
|
||||
/**
|
||||
* 创建客户端
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public static OkHttpClient.Builder ofHttpClient() {
|
||||
OkHttpClient.Builder builder = new OkHttpClient.Builder()
|
||||
.connectTimeout(OkHttpConfig.GLOBAL_TIMEOUT, TimeUnit.MILLISECONDS)
|
||||
.readTimeout(OkHttpConfig.GLOBAL_TIMEOUT, TimeUnit.MILLISECONDS);
|
||||
|
||||
for (Interceptor interceptor : OkHttpConfig.INTERCEPTORS) {
|
||||
builder.addInterceptor(interceptor);
|
||||
}
|
||||
|
||||
return builder;
|
||||
}
|
||||
|
||||
public static Request ofRequest(String method, String url, RequestBody body) {
|
||||
return new Request.Builder()
|
||||
.url(url).method(method, body).build();
|
||||
}
|
||||
|
||||
public static Request ofGet(String url) {
|
||||
return ofRequest("GET", url, null);
|
||||
}
|
||||
|
||||
public static Request ofPost(String url, JSONObject body) {
|
||||
return ofRequest("POST", url, ofJsonBody(body.toString()));
|
||||
}
|
||||
|
||||
public static Request ofPost(String url, RequestBody body) {
|
||||
return ofRequest("POST", url, body);
|
||||
}
|
||||
|
||||
public static RequestBody ofJsonBody(String json) {
|
||||
return RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
|
||||
}
|
||||
|
||||
public static ResponseBody ofJsonResponse(String json) {
|
||||
return ResponseBody.create(MediaType.parse("application/json; charset=utf-8"), json);
|
||||
}
|
||||
|
||||
public static MultipartBody.Builder ofMultipartBody(File file) {
|
||||
return new MultipartBody.Builder()
|
||||
.setType(MultipartBody.FORM)
|
||||
.addFormDataPart("file", file.getName(),
|
||||
RequestBody.create(MediaType.parse("application/octet-stream"), file));
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// get请求
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
|
||||
public static String get(String urlString) {
|
||||
return get(urlString, OkHttpConfig.GLOBAL_TIMEOUT);
|
||||
}
|
||||
|
||||
public static String get(String urlString, Map<String, Object> queryMap) {
|
||||
String build = UrlQuery.of(queryMap).build(CharsetUtil.CHARSET_UTF_8);
|
||||
if (StrUtil.contains(urlString, "?")) {
|
||||
urlString = urlString + "&" + build;
|
||||
} else {
|
||||
urlString = urlString + "?" + build;
|
||||
}
|
||||
return get(urlString, OkHttpConfig.GLOBAL_TIMEOUT);
|
||||
}
|
||||
|
||||
public static String get(String urlString, int timeout) {
|
||||
try {
|
||||
return ofHttpClient().connectTimeout(timeout, TimeUnit.MILLISECONDS)
|
||||
.build().newCall(ofGet(urlString)).execute().body().string();
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// Post请求
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
|
||||
public static String post(String urlString, Map<String, String> paramMap) {
|
||||
return post(urlString, paramMap, OkHttpConfig.GLOBAL_TIMEOUT);
|
||||
}
|
||||
|
||||
public static String post(String urlString, Map<String, String> paramMap, int timeout) {
|
||||
FormBody.Builder formBuilder = new FormBody.Builder();
|
||||
for (String key : paramMap.keySet()) {
|
||||
formBuilder.add(key, paramMap.get(key));
|
||||
}
|
||||
return post(urlString, formBuilder.build(), timeout);
|
||||
}
|
||||
|
||||
public static String post(String urlString, JSONObject body) {
|
||||
return post(urlString, body, OkHttpConfig.GLOBAL_TIMEOUT);
|
||||
}
|
||||
|
||||
public static String post(String urlString, JSONObject body, int timeout) {
|
||||
return post(urlString, ofJsonBody(body.toString()), timeout);
|
||||
}
|
||||
|
||||
public static String post(String urlString, RequestBody body, int timeout) {
|
||||
try {
|
||||
return ofHttpClient().connectTimeout(timeout, TimeUnit.MILLISECONDS)
|
||||
.build().newCall(ofPost(urlString, body)).execute().body().string();
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// Download下载文件
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
|
||||
public static File downloadFile(String url, String destFile) {
|
||||
return downloadFile(url, FileUtil.file(destFile));
|
||||
}
|
||||
|
||||
public static File downloadFile(String url, File destFile) {
|
||||
try {
|
||||
Response response = ofHttpClient()
|
||||
.connectTimeout(0, TimeUnit.MILLISECONDS)
|
||||
.readTimeout(0, TimeUnit.MILLISECONDS)
|
||||
.build().newCall(ofGet(url)).execute();
|
||||
if (response.isSuccessful() && response.body() != null) {
|
||||
FileUtil.writeFromStream(response.body().byteStream(), destFile);
|
||||
}
|
||||
return destFile;
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static byte[] downloadBytes(String url) {
|
||||
try {
|
||||
Response response = ofHttpClient()
|
||||
.connectTimeout(0, TimeUnit.MILLISECONDS)
|
||||
.readTimeout(0, TimeUnit.MILLISECONDS)
|
||||
.build().newCall(ofGet(url)).execute();
|
||||
if (response.isSuccessful() && response.body() != null) {
|
||||
return response.body().bytes();
|
||||
}
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user