RestTemplate发送post、get请求
使用RestTemplate发送post请求
public String restTemplateByPost(String apiUrl, Map<String,String> reqParam, MediaType accept){
String body = null;
try{
//获取数据接口
log.debug("请求的参数为{}",reqParam.toString());
log.debug("请求地址为{}",apiUrl);
//创建请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
//通过设置 Accept,服务端就可以在响应头中设置正确的 Content-Type 类型,以确保客户端在接收响应时将其正确解析
if(accept != null){
headers.setAccept(Arrays.asList(accept));
}
//创建请求对象
Map<String, Object> postParameters = new HashMap<>();
reqParam.forEach((k,v) -> {
postParameters.put(k, v);
});
HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(postParameters, headers);
ResponseEntity<String> res = restTemplate.exchange(apiUrl, HttpMethod.POST, requestEntity, String.class);
body = res.getBody();
log.debug("调用三方远程请求的返回为:{}",body);
// int statusCode = res.getStatusCodeValue();
// if(statusCode != 201 && statusCode != 200){
// log.info("调用三方接口返回异常{}:",body);
// throw new RuntimeException("调用三方接口返回异常:"+body);
// }
}catch (Exception e){
log.error(e.getMessage());
throw new RunTimeCoreException("001","调用三方接口异常:"+e.getMessage());
}
if(StringUtils.isBlank(body)){
throw new RunTimeCoreException("002","调用三方接口返回异常:"+body);
}
return body;
}
使用RestTemplate发送get请求
public String restTemplateByGet(String apiUrl, Map<String,String> reqParam){
log.debug("请求的参数为{}",reqParam.toString());
log.debug("请求地址为{}",apiUrl);
// JSONObject jsonObject = null;
String body = null;
try{
//创建请求头
HttpHeaders headers = new HttpHeaders();
HttpEntity<MultiValueMap<String,String>> request = new HttpEntity(null,headers);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(apiUrl);
ResponseEntity<String> res;
//如果存在參數
if(!reqParam.isEmpty()){
for (Map.Entry<String,String> e: reqParam.entrySet()) {
//构建查询参数
builder.queryParam(e.getKey(),e.getValue());
}
//拼接好参数后的URl//test.com/url?param1={param1}¶m2={param2};
String reallyUrl=builder.build().toString();
log.info("发送get请求拼接好参数的Url:{}",reallyUrl);
res =restTemplate.exchange(reallyUrl, HttpMethod.GET,request,String.class);
}else{
res=restTemplate.exchange(apiUrl,HttpMethod.GET,request,String.class);
}
body = res.getBody();
log.debug("调用三方远程请求的返回为:{}",body);
// jsonObject = JSON.parseObject(body);
}catch (Exception e){
log.error(e.getMessage());
throw new RunTimeCoreException("001","调用三方接口异常:"+e.getMessage());
}
if(StringUtils.isBlank(body)){
throw new RunTimeCoreException("002","调用三方接口返回异常:"+body);
}
// return body;
return body;
}