说明:之前一直使用的非Spring框架,没用框架进行开发,所以,所有的接口调用用的都是HTTP Client。现在使用SpringBoot框架,让我也来试试比较方便的restTemplate接口调用吧。
其中,下方也 设置了请求头、请求体
需求:使用POST请求将json数据,传到接口方。
public void news() {
//接口地址
String url = "接口的地址ip:port/路径";
newsDTO newsDTO = new newsDTO();
newsDTO.setNewsId("id");
newsDTO.setTitle("标题");
log.info("这是实体类信息:----------"+newsDTO.toString());
//调用restTemplate接口,插入数据
JSONObject restTem = getRestTem(url, JSONUtil.toJsonStr(newsDTO));
log.info("这是返回值 : "+ restTem);
}
//restTemplate 接口调用
public JSONObject getRestTem(String url, String message){
//设置请求头
HttpHeaders httpHeaders = new HttpHeaders();
//传递请求体时必须设置传递参数的格式,为Content-Type : application/json
httpHeaders.add("Content-Type", "application/json;charset=UTF-8");
// TODO 其他需要设置的请求头
httpHeaders.add("headerName1", "headerValue1");
// 2.请求头 & 请求体
HttpEntity<JSON> fromEntity = new HttpEntity(message, headers);
// 地址 请求头+体 返回类型
JSONObject forObject = restTemplate.postForObject(url, fromEntity, JSONObject.class);
return forObject;
}