2022-11-10 21:55:46
浏览数 (1)
导入依赖
代码语言:javascript
复制import org.springframework.web.client.RestTemplate;
创建工具类
代码语言:javascript
复制@Component
@Slf4j
public class RestTemplateUtil {
@Resource
private RestTemplate restTemplate;
/**
* 配置请求超时时间
*/
public final HttpComponentsClientHttpRequestFactory httpRequestFactory() {
HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
httpRequestFactory.setConnectionRequestTimeout(3000);
httpRequestFactory.setConnectTimeout(3000);
httpRequestFactory.setReadTimeout(3000);
return httpRequestFactory;
}
/**
* 处理状态码非200的情况
* @return ResponseErrorHandler
*/
public final ResponseErrorHandler responseErrorHandler(){
return new ResponseErrorHandler() {
@Override
public boolean hasError(@NotNull ClientHttpResponse clientHttpResponse) {
return true;
}
@Override
public void handleError(@NotNull ClientHttpResponse clientHttpResponse){
}
};
}
public Object execute(EntranceDto entranceDto, List<NameValuePair> queryParams, Map<String, Object> headerMap, JSONObject requestBody)
throws URISyntaxException, RestClientException {
//设置HEADER参数
HttpHeaders headerParams = getHeaderParams(headerMap);
//设置body 和 header
HttpEntity<String> requestEntity;
if (requestBody!=null&&!requestBody.toString().equals("{}")) {
requestEntity = new HttpEntity<>(requestBody.toString(), headerParams);
}else {
requestEntity = new HttpEntity<>(headerParams);
}
//构造请求url
URI url = new URIBuilder()
.setScheme(entranceDto.getEntranceType().getDescription().toLowerCase())
.setHost(entranceDto.getIp())
.setPort(entranceDto.getPort())
.setPath(entranceDto.getPath())
.setParameters(queryParams)
.build();
String resultString;
//设置响应字符集
StringHttpMessageConverter converter=new StringHttpMessageConverter(StandardCharsets.UTF_8);
//设置超时时间
restTemplate.setRequestFactory(httpRequestFactory());
restTemplate.setMessageConverters(Collections.singletonList(converter));
restTemplate.setErrorHandler(responseErrorHandler());
switch (entranceDto.getMethod()) {
case GET:
resultString = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class).getBody();
break;
case PUT:
resultString = restTemplate.exchange(url, HttpMethod.PUT, requestEntity, String.class).getBody();
break;
case POST:
resultString = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class).getBody();
break;
case DELETE:
resultString = restTemplate.exchange(url, HttpMethod.DELETE, requestEntity, String.class).getBody();
break;
default:
throw new CommonException("请求类型异常不属于GET,POST,PUT,DELETE" entranceDto.getMethod());
}
if (getJsonType(resultString)) {
return JSONUtil.parseObj(resultString);
} else {
return resultString;
}
}
private static HttpHeaders getHeaderParams(Map<String, Object> map) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.parseMediaType("application/json;charset=UTF-8"));
httpHeaders.add("Accept", MediaType.APPLICATION_JSON.toString());
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (entry.getValue() != null) {
httpHeaders.add(entry.getKey(), entry.getValue().toString());
}
}
return httpHeaders;
}
/**
* 判断是否为简单的json
*
* @param str json字符串
* @return boolean
*/
public static boolean getJsonType(String str) {
boolean result = false;
if (!StringUtils.isBlank(str)) {
str = str.trim();
if (str.startsWith("{") && str.endsWith("}")) {
result = true;
} else if (str.startsWith("[") && str.endsWith("]")) {
result = true;
}
}
return result;
}
}