通用配置:
package com.example.demo.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.client.ClientHttpRequestFactory;
/**
* RestTemplate配置类
*/
@Configuration
public class RestTemplateConfig extends RestTemplate {
private int restTemplateTimeout = 10 ;
@Bean
public RestTemplate restTemplate() {
return new RestTemplate(clientHttpRequestFactory());
}
@Bean
public ClientHttpRequestFactory clientHttpRequestFactory() {
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
//读取超时,单位:毫秒
factory.setReadTimeout(1000 * restTemplateTimeout);
//连接超时,单位:毫秒
factory.setConnectTimeout(1000 * restTemplateTimeout);
factory.setConnectionRequestTimeout(1000 * restTemplateTimeout);
return factory;
}
}
返回值(里面用到了 swagger,不需要的可以把相关标签删除):
package com.example.demo.utils;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
/**
* @author Rain
* @date 2023/11/30
*/
@ApiModel(description= "响应数据结构")
@Data
public class Result<T> implements Serializable {
@ApiModelProperty(value = "响应代码{<br />" +
"Success(0),//基本符合预期<br />" +
"<br />" +
" Failure(-1), //虽然异常,但无法提供更多额外信息<br />" +
"<br />" +
" FAILED_InvalidParameter(-2),//无效参数,不符合服务端基本校验要求<br />" +
"<br />" +
" FAILED_UnsupportedDataSourceType(-3),//数据源类型不支持<br />" +
"<br />" +
" FAILED_UnauthorizedCodeOfDataLake(-4),//您的 code 未经授权,无法提供token<br />" +
"<br />" +
" FAILED_NoDataMatchConditions(-5),//您的没有数据能够匹配您的条件查询<br />" +
"<br />" +
" ERROR_DataSourceServerAccessIsNotResponded(-6),//数据源服务器访问异常<br />" +
"<br />" +
" ERROR_ServerIsError(-7);//零件查询服务异常<br />" +
"<br />" +
" ERROR_InvalidToken(-8);//无效 token<br />" +
"<br />" +
" ERROR_TokenIsExpirated(-9);//token 过期<br />" +
"<br />" +
" FAILED_NoLoginPermissionIsRejected(-10);//您的 accessToken 免登录请求无效,无法提供token<br />" +
"<br />" +
" FAILED_NoLoginPermissionIsExpirated(-11),;//您的 accessToken 免登录过期,无法提供token<br />" +
"}")
private Integer code;
@ApiModelProperty(value = "响应信息")
private String msg;
@ApiModelProperty(value = "数据")
private T data;
private Result(){
}
private static <T> Result<T> build(Label label) {
return build(label, null);
}
private static <T> Result<T> build(Label label, T result) {
return build(label, label.name(), result);
}
private static <T> Result<T> build(Label label, String message, T result) {
Result<T> resultJson = new Result<>();
resultJson.code = label.code;
resultJson.msg = message;
resultJson.data = result;
return resultJson;
}
public static enum Label {
/**
* code 遵守如下约定:
* 正数 代表 期望现象;
* 负值 代表悲观现象;
* 0 代表 基本符合预期。
*/
Success(0),//基本符合预期
/**
* 虽然异常,但无法提供更多额外信息
*/
Failure(-1), 虽然异常,但无法提供更多额外信息
/**
* 无效参数
* 不符合服务端基本校验要求
*/
FAILED_InvalidParameter(-2),//无效参数,不符合服务端基本校验要求
/**
* 数据源类型不支持
*/
FAILED_UnsupportedDataSourceType(-3),//数据源类型不支持
/**
* 您的 code 未经授权,无法提供token
*/
FAILED_UnauthorizedCodeOfDataLake(-4),//您的 code 未经授权,无法提供token
/**
* 您的没有数据能够匹配您的条件查询
*/
FAILED_NoDataMatchConditions(-5),//您的没有数据能够匹配您的条件查询
/**
* 数据源服务器访问异常
*/
ERROR_DataSourceServerAccessIsNotResponded(-6),//数据源服务器访问异常
/**
* 零件查询服务异常
*/
ERROR_ServerIsError(-7),//零件查询服务异常
/**
* 无效 token
*/
ERROR_InvalidToken(-8),//无效 token
/**
* token 过期
*/
ERROR_TokenIsExpirated(-9),//token 过期
/**
* 您的 accessToken 免登录请求无效,无法提供token
*/
FAILED_NoLoginPermissionIsRejected(-10),//您的 accessToken 免登录请求无效,无法提供token
/**
* 您的 accessToken 免登录过期,无法提供token
*/
FAILED_NoLoginPermissionIsExpirated(-11),//您的 accessToken 免登录过期,无法提供token
;
private Integer code;
Label(Integer code) {
this.code = code;
}
public <T> Result<T> as(){
return Result.build(this);
}
public <T> Result<T> as(T data){
return Result.build(this,data);
}
}
}
这里直接写 service-impl层(两种 post 方式,算是抛砖引入):
@Autowired
private RestTemplateConfig restTemplate;
@Override
public void list4Parts(VOSearch vo) {
// 方法1
String url = "https://www.baidu.com/";
//拼凑返回值
Result<Map<String, Object>> result = this.restTemplate.postForObject(url, this.getHttpEntity(vo), Result.class);
// 方法2
//拼凑返回值
Map<String, String> body = new HashMap<>();
body.put("option", option);
body.put("optionVersion", optionVersion);
ResponseEntity<Result> tokenResponse = this.restTemplate.exchange(url, HttpMethod.POST, this.getHttpEntity(body), Result.class);
// 获取token响应的body
Result<Map<String, Object>> result = tokenResponse.getBody();
}
/**
* 获取单个 VOSearch 的 json 参数结构体
*
* @return HttpEntity
*/
private HttpEntity<VOSearch> getHttpEntity(VOSearch vo) {
//准备参数
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return new HttpEntity<>(vo, headers);
}
/**
* 获取单个 key-value 的 json 参数结构体
*
* @return HttpEntity
*/
private HttpEntity<Map<String, String>> getHttpEntity(Map<String, String> body) {
//准备参数
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return new HttpEntity<>(body, headers);
}