RestTemplate发送POST请求
程序员文章站
2022-06-24 21:55:57
...
RestTemplate发送POST请求
在java后端实现发送Http的post请求,做个记录
1.首先创建一个对请求返回数据进行处理的类
public class ResultVO<T> {
private Integer code;
private String message;
private T data;
public ResultVO() {
}
public ResultVO(Integer code, String message) {
this.code = code;
this.message = message;
}
public ResultVO(Integer code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
2.发送请求(post+params)
public class MyUtils {
/**
* 向目的URL发送post请求
* @param url 目的url
* @param params 发送的参数
* @return ResultVO
*/
public static ResultVO sendPostRequest(String url, MultiValueMap<String, String> params){
RestTemplate client = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
HttpMethod method = HttpMethod.POST;
// 以表单的方式提交
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//将请求头部和参数合成一个请求
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
//执行HTTP请求,将返回的结构使用ResultVO类格式化
ResponseEntity<ResultVO> response = client.exchange(url, method, requestEntity, ResultVO.class);
return response.getBody();
}
}
3.具体使用
private ResultVO setShelveData(String sensorCode, String temperature,String humidity) {
String url = "http://xxxx/api/setShelveData";
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("sensorCode", sensorCode);
params.add("temperature", temperature);
params.add("humidity", humidity);
//发送Post数据并返回数据
ResultVO resultVo = MyUtils.sendPostRequest(url, params);
return resultVo;
}
转载于:https://blog.csdn.net/zai_xia/article/details/80926157