RestTemplate exchange GET POST请求传参数DEMO
link:
Illegal character ((CTRL-CHAR, code 31))问题排查 gzip接口返回 RestTemplate GET POST请求
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;
@Service
public class RestTemplateRemoteService {
@Autowired
private RestTemplate restTemplate;
private static final Logger logger = LoggerFactory.getLogger(RestTemplateRemoteService.class);
/**
* 新增记录接口
* @param violationAdditionRequestVO
* @return
*/
public ResponseData save(AdditionRequestVO additionRequestVO) {
String wzServiceUrl = "http://xxx";
String reqUrl = wzServiceUrl + "/public/order/add";
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
String reqJson = new Gson().toJson(additionRequestVO);
logger.info("remote save url=[{}],params=[{}]",reqUrl,reqJson);
HttpEntity<String> httpEntity = new HttpEntity<String>(reqJson, httpHeaders);
ParameterizedTypeReference<ResponseData> typeRef = new ParameterizedTypeReference<ResponseData>() {
};
try {
ResponseData response = restTemplate.exchange(reqUrl, HttpMethod.POST, httpEntity, typeRef).getBody();
logger.info("remote save url=[{}],result=[{}]",reqUrl,new Gson().toJson(response));
return response;
}catch(Exception e) {
logger.error("新增接口异常:", e);
}
return null;
}
public MyDepositResVO getInfo(String orderNo) {
String wzServiceUrl = "http://xxx";
String reqUrl = wzServiceUrl + "/public/order/get?orderNo="+orderNo;
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
//GET请求方式,直接跟在url参数后面拼接
// Map<String, Object> reqMap = new HashMap<>();
// reqMap.put("orderNo", orderNo);
// String reqJson = new Gson().toJson(reqMap);
logger.info("remote getInfo url=[{}],params=[{}]",reqUrl,orderNo);
HttpEntity<String> httpEntity = new HttpEntity<String>(null, httpHeaders);
ParameterizedTypeReference<ResponseData<MyDepositResVO>> typeRef = new ParameterizedTypeReference<ResponseData<MyDepositResVO>>() {
};
try {
ResponseData response = restTemplate.exchange(reqUrl, HttpMethod.GET, httpEntity, typeRef).getBody();
logger.info("remote getInfo url=[{}],result=[{}]",reqUrl,new Gson().toJson(response));
if(response != null && ErrorCode.SUCCESS.getCode().equals(response.getResCode())){
return (MyDepositResVO) response.getData();
}
}catch(Exception e) {
logger.error("查询接口异常:", e);
}
return null;
}
}
//
public class ResponseData<T> {
@AutoDocProperty("返回代码")
private String resCode;
@AutoDocProperty("返回消息")
private String resMsg;
@AutoDocProperty("返回实体")
private T data;
}