赞
踩
在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 */ //a.以表单方式提交 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(); } //b.以json方式提交 public static ResultVO sendPostRequest1(String url, Map<String, Object> params){ RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity entity = new HttpEntity(params, headers); ResultVO response = restTemplate.postForObject(url, entity, ResultVO.class); return response; } }
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 http://www.manongjc.com/article/38034.html
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。