使用RestTemplate发送Post请求
程序员文章站
2022-06-24 23:40:08
...
参数类
import com.alibaba.fastjson.annotation.JSONField;
import com.DbProperties; //这是自定义的一个类
import lombok.Data;
@Data
public class TrafficCountPredictionParam {
/**
* 请求的唯一标识
*/
@JSONField(name = "trace_id")
private String traceId;
@JSONField(name = "db_original")
private DbProperties dbOriginal = new DbProperties();
@JSONField(name = "db_statistics")
private DbProperties dbStatistics = new DbProperties();
/**
* 路段ID,用逗号分隔
*/
@JSONField(name = "unit_id")
private String unitId;
/**
* 请求接口地址
*/
private String address;
@JSONField(name = "custom_days")
private CustomDays customDays = new CustomDays();
/**
* 当前日期
*/
@JSONField(name = "current_date")
private String currentDate;
/**
* 时间类型
*/
@JSONField(name = "time_type")
private Integer timeType;
@Data
public static class CustomDays {
/**
* 开始日期
*/
@JSONField(name = "start_date")
private String startDate;
/**
* 结束日期
*/
@JSONField(name = "end_date")
private String endDate;
}
}
代码实现:
private boolean predictionApi(String url, TrafficCountPredictionParam param, int count) {
boolean flag = true;
if (count == 0) {
RestTemplate template = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
String content = JSON.toJSONString(param);
HttpEntity<String> request = new HttpEntity<>(content, headers);
final ResponseEntity<String> responseEntity;
try {
responseEntity = template.postForEntity(url, request, String.class);
final String body = responseEntity.getBody();
final JSONObject responseBody = JSON.parseObject(body);
final Object statue = responseBody.get("status");
if (!"OK".equals(statue)) {
flag = false;
}
} catch (Exception e) {
e.printStackTrace();
flag = false;
}
}
return flag;
}
上一篇: RestTemplate 发送http post请求
下一篇: 预算够的,上化妆师吧