首先创建一个RestTemplate
对象
@Bean
public RestTemplate restTemplate(){
RestTemplate restTemplate = new RestTemplate();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
/**
* 使用客户端类API调用远程交易时必须设置相应的超时时间,如果远程交易有问题如长时间未响应,若未设置超时时间,则会耗尽客户端所在服务器的资源
*/
// 连接超时
requestFactory.setConnectTimeout(5000);
//读超时
requestFactory.setReadTimeout(10000);
//连接池获取连接超时时间
requestFactory.setConnectionRequestTimeout(5000);
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
//Httpclient连接池的方式,同时支持netty,okHttp以及其他http框架
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
// 最大连接数
connectionManager.setMaxTotal(200);
// 同路由并发数
connectionManager.setDefaultMaxPerRoute(50);
//配置连接池
httpClientBuilder.setConnectionManager(connectionManager);
// 最大连接数
connectionManager.setMaxTotal(500);
// 同路由并发数(每个主机的并发)
connectionManager.setDefaultMaxPerRoute(100);
httpClientBuilder.setConnectionManager(connectionManager);
requestFactory.setHttpClient(httpClientBuilder.build());
restTemplate.setRequestFactory(requestFactory);
return restTemplate;
}
封装请求工具HttpUtil
package com.demo;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/** HttpUtil
* author chics
* 2023/8/22
*/
@Slf4j
@Component
public class HttpUtil {
public static final String API_KEY_PREFIX = "Api_key";
public static RestTemplate restTemplate;
@Autowired
public void setRestTemplate(RestTemplate restTemplate) {
HttpUtil.restTemplate = restTemplate;
}
/**
* get请求
* @param apiKey
* @param uri
* @param clazz
* @return
*/
public static <T>T get(String apiKey,String uri,Class<T> clazz){
return get(apiKey,uri,null,null,clazz);
}
/**
* get请求
* @param apiKey
* @param uri
* @param body
* @param clazz
* @return
*/
public static <T>T get(String apiKey,String uri,Object body,Class<T> clazz){
return get(apiKey,uri,body,null,clazz);
}
/**
* get请求
* @param apiKey
* @param uri
* @param formParams
* @param clazz
* @return
*/
public static <T>T get(String apiKey,String uri,Map<String,Object> formParams,Class<T> clazz){
return get(apiKey,uri,null,formParams,clazz);
}
/**
* get请求
* @param apiKey
* @param uri
* @param body
* @param formParams
* @param clazz
* @return
*/
public static <T>T get(String apiKey,String uri,Object body,Map<String,Object> formParams,Class<T> clazz){
HttpEntity<Object> httpEntity = new HttpEntity<Object>(null, getHttpHeaders(apiKey));
if (!ObjectUtils.isEmpty(body)){
httpEntity = new HttpEntity<Object>(body, getHttpHeaders(apiKey));
}
if (ObjectUtils.isEmpty(formParams)){
ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.GET, httpEntity, String.class);
return JSON.parseObject(result.getBody(),clazz);
}
ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.GET,httpEntity,String.class,formParams);
return JSON.parseObject(result.getBody(),clazz);
}
/**
* post请求
* @param apiKey
* @param uri
* @param clazz
* @return
*/
public static <T>T post(String apiKey,String uri,Class<T> clazz){
return post(apiKey,uri,null,null,clazz);
}
/**
* post请求
* @param apiKey
* @param uri
* @param body
* @param clazz
* @return
*/
public static <T>T post(String apiKey,String uri,Object body,Class<T> clazz){
return post(apiKey,uri,body,null,clazz);
}
/**
* post请求
* @param apiKey
* @param uri
* @param formParams
* @param clazz
* @return
*/
public static <T>T post(String apiKey,String uri,Map<String,Object> formParams,Class<T> clazz){
return post(apiKey,uri,null,formParams,clazz);
}
/**
* post请求
* @param apiKey
* @param uri
* @param body
* @param formParams
* @param clazz
* @return
*/
public static <T>T post(String apiKey,String uri,Object body,Map<String,Object> formParams,Class<T> clazz){
HttpEntity<Object> httpEntity = new HttpEntity<Object>(null, getHttpHeaders(apiKey));
if (!ObjectUtils.isEmpty(body)){
httpEntity = new HttpEntity<Object>(body, getHttpHeaders(apiKey));
}
if (ObjectUtils.isEmpty(formParams)){
ResponseEntity<String> result = restTemplate.postForEntity(uri, httpEntity, String.class);
return JSON.parseObject(result.getBody(),clazz);
}
ResponseEntity<String> result = restTemplate.postForEntity(uri, httpEntity, String.class,formParams);
return JSON.parseObject(result.getBody(),clazz);
}
/**
* post文件上传请求
* @param apiKey
* @param uri
* @param formParams
* @param clazz
* @return
*/
public static <T>T postUpload(String apiKey, String uri, MultiValueMap<String,Object> formParams,Class<T> clazz){
//设置请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
headers.add(API_KEY_PREFIX,apiKey);
/*MultiValueMap<String,Object> form = new LinkedMultiValueMap<>();
for (int i = 0; i < files.size(); i++) {
MultipartFile file = files.get(i);
form.add("files", file.getResource());
}*/
HttpEntity<Object> httpEntity = new HttpEntity<>(formParams, headers);
ResponseEntity<String> result = restTemplate.postForEntity(uri, httpEntity, String.class);
return JSON.parseObject(result.getBody(),clazz);
}
/**
* 创建上传文件createForm
* @return
*/
public static MultiValueMap<String,Object> createForm(){
return new LinkedMultiValueMap<>();
}
/**
* 获取文件流
* @param apiKey
* @param uri
* @return
*/
public static byte[] getFileStream(String apiKey,String uri){
HttpHeaders headers = new HttpHeaders();
headers.add(API_KEY_PREFIX,apiKey);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_OCTET_STREAM));
HttpEntity<String> entity = new HttpEntity<String>(headers);
ResponseEntity<byte[]> response = restTemplate.exchange(uri, HttpMethod.GET, entity, byte[].class);
return response.getBody();
}
/**
* 获取请求头
* @param apiKey
* @return
*/
private static HttpHeaders getHttpHeaders(String apiKey){
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add(API_KEY_PREFIX,apiKey);
return headers;
}
/**
* 序列化成集合
* @param data
* @param clazz
* @param <T>
* @return
*/
public static <T>List<T> toList(Object data,Class<T> clazz){
return JSON.parseArray(JSON.toJSONString(data)).toJavaList(clazz);
}
}
使用就是根据方法参数传值就行。如下:
/**
* 上传
* @param requestBody
* @return
*/
public static OSSResponseBody upload(OSSRequestBody requestBody){
MultiValueMap<String, Object> form = HttpUtil.createForm();
form.add("file",requestBody.getFile().getResource());
form.add("dir",requestBody.getDir());
R r = HttpUtil.postUpload(null, instance.uploadHost + "/zyq/file/upload", form, R.class);
log.info("上传:{}", JSONUtil.toJsonStr(r));
return JSONUtil.toBean(JSONUtil.toJsonStr(r.getData()),OSSResponseBody.class);
}
// 调用
public R<String> upload(MultipartFile file) {
OSSRequestBody ossRequestBody = new OSSRequestBody();
ossRequestBody.setFile(file);
OSSResponseBody responseBody = FileUploadUtil.upload(ossRequestBody);
if (responseBody.isSuccess()){
// ....
}
}
是不是调用就简单多了。用到的类
OSSRequestBody
package com.zyq.vo;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
/** OSSRequestBody
* author xiaochi
* date 2024/5/28 17:03
*/
public class OSSRequestBody {
private List<MultipartFile> files;// 多文件上传
private MultipartFile file;// 单文件上传
private String filePath;// 可不传
private String dir;// 可不传
public List<MultipartFile> getFiles() {
return files;
}
public void setFiles(List<MultipartFile> files) {
this.files = files;
}
public MultipartFile getFile() {
return file;
}
public void setFile(MultipartFile file) {
this.file = file;
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public String getDir() {
return dir;
}
public void setDir(String dir) {
this.dir = dir;
}
}
OSSResponseBody
package com.zyq.vo;
import lombok.Data;
/** OSSResponseBody
* author xiaochi
* date 2024/5/28 16:28
*/
@Data
public class OSSResponseBody {
private String viewPath;
private String path;
private boolean success;
private String errorMsg;
private String errorCode;
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
}
到此完成。