使用RestTemplate的POST请求http://www.ousuiot.com:9801/querypubdata,用实体类接收结果集 请求参数: { "signature":"FC73D944C6E54087ABDC3F71AD7857BF", "deviceid":"230417100002" } 请求结果: {"code":200,"deviceid":"230417100002","data":[{"channelid":1,"devname":"温度","devvalue":"35.3","devunit":"℃","devtime":"2023-06-02 16:18:54"},{"channelid":2,"devname":"湿度","devvalue":"46.6","devunit":"%RH","devtime":"2023-06-02 16:18:54"},{"channelid":3,"devname":"光照度","devvalue":"8960","devunit":"Lux","devtime":"2023-06-02 16:18:54"},{"channelid":4,"devname":"二氧化碳","devvalue":"457","devunit":"ppm","devtime":"2023-06-02 16:18:54"},{"channelid":5,"devname":"土壤温度","devvalue":"40.1","devunit":"℃","devtime":"2023-06-02 16:18:54"},{"channelid":6,"devname":"土壤湿度","devvalue":"25.1","devunit":"%","devtime":"2023-06-02 16:18:54"},{"channelid":7,"devname":"土壤电导率","devvalue":"200","devunit":"μS/cm","devtime":"2023-06-02 16:18:54"},{"channelid":8,"devname":"土壤pH值","devvalue":"6.8","devunit":"pH","devtime":"2023-06-02 16:18:54"},{"channelid":9,"devname":"土壤氮含量","devvalue":"15","devunit":"mg/Kg","devtime":"2023-06-02 16:18:54"},{"channelid":10,"devname":"土壤磷含量","devvalue":"21","devunit":"mg/Kg","devtime":"2023-06-02 16:18:54"},{"channelid":11,"devname":"土壤钾含量","devvalue":"53","devunit":"mg/Kg","devtime":"2023-06-02 16:18:54"}]}
时间: 2023-08-22 13:06:23 浏览: 275
根据上面的请求参数和请求结果,你可以定义一个实体类`ResultEntity`来接收返回结果:
```java
public class ResultEntity {
private Integer code;
private String deviceid;
private List<DataEntity> data;
// getters and setters
}
public class DataEntity {
private Integer channelid;
private String devname;
private String devvalue;
private String devunit;
private String devtime;
// getters and setters
}
```
然后使用RestTemplate发送POST请求并接收结果:
```java
RestTemplate restTemplate = new RestTemplate();
String url = "http://www.ousuiot.com:9801/querypubdata";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
Map<String, String> requestMap = new HashMap<>();
requestMap.put("signature", "FC73D944C6E54087ABDC3F71AD7857BF");
requestMap.put("deviceid", "230417100002");
HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(requestMap, headers);
ResponseEntity<ResultEntity> responseEntity = restTemplate.postForEntity(url, requestEntity, ResultEntity.class);
ResultEntity result = responseEntity.getBody();
```
这样,`result`对象就包含了返回结果中的所有信息。可以通过`result.getCode()`获取返回的状态码,通过`result.getData()`获取设备数据列表。需要注意的是,`ResultEntity`中的属性名要与返回结果中的字段名一致。
阅读全文