通过new RestTemplate()测试接口
package com.ml.app.pms.gh;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
@Slf4j
public class WebServiceTest {
String ghRequestUrl = "http://XXX/find";
@Test
public void web_service_test() {
String sendJson = "{\"op\":\"findSalary\", \"yearMonth\":\"202201\"}";
String resultStr = sendPostRequest(ghRequestUrl, sendJson);
System.out.println("返回:" + resultStr);
}
private String sendPostRequest(String url, String params) {
RestTemplate client = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth("ceshi", "ceshi123");
HttpMethod method = HttpMethod.POST;
// 以表单的方式提交 application/json
headers.setContentType(MediaType.APPLICATION_JSON);
//将请求头部和参数合成一个请求
HttpEntity<String> requestEntity = new HttpEntity<>(params, headers);
//执行HTTP请求,将返回的结构使用ResultVO类格式化
ResponseEntity<String> response = client.exchange(url, method, requestEntity, String.class);
return response.getBody();
}
}
采用RestTemplateBuilder构建RestTemplate(实际应用)
@Slf4j
@Component
@ConditionalOnProperty({
"xxx.url",
})
public class HttpXxxInterfaceClient implements IHttpXxxInterfaceClient {
private final RestTemplate restTemplate;
private final String serverHost;
public HttpBbguInterfaceClient(RestTemplateBuilder builder, @Value("${xxx.url}") String serverHost) {
this.restTemplate = builder
.setConnectTimeout(Duration.ofMinutes(5))
.setReadTimeout(Duration.ofMinutes(5))
.build();
this.serverHost = serverHost;
}
}
// 调用接口并返回
private <T> List<T> doRequest(Object request, Class<T> responseClass) {
log.trace("Begin URL->{}, requestBody is {}", this.serverHost, request.toString());
try {
String resp = this.restTemplate.postForObject(this.serverHost, request, String.class);
InterfaceResult apiResult = JSON.parseObject(resp, InterfaceResult.class);
if (Objects.isNull(apiResult)) {
throw BusinessException.withArgs(ErrorCode.ERR_10500, "返回异常,返回信息为空");
}
return JSONObject.parseArray(apiResult.getDATA(), responseClass);
} catch (BusinessException ex) { // 自己抛出来的ex
throw ex;
} catch (Exception ex) {
log.error("bbgu invoke error[class={}, msg={}]", ex.getClass(), ex.getLocalizedMessage());
String errorMessage = String.format("bbgu invoke error[class=%s, msg=%s]", ex.getClass(), ex.getLocalizedMessage());
throw BusinessException.withArgs(ErrorCode.ERR_10500, errorMessage);
}
}