2024-10-28
最近的一个工作任务是把一些关系数据接口入库的工作
首先要注意的点
a)、返回的数据类型的list<>
b)、对接第三方接口,接口返回的数据是json格式的,有分页
c)、请求方式均为Http协议Post请求,我选择用原始的RestTemplate来调用
1,需求不难,拿到分页页数就可以判断要请求多少次。

2,只需要通过RestTemplate工具发起请求
通过RestTemplate发起post请求,携带页数请求返回全部记录
public String post(String url, String page) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> httpEntity = new HttpEntity<>(page, headers);
ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
if (exchange.getStatusCode() != HttpStatus.OK) {
return "error";
}
return exchange.getBody();
}
3,把返回字符串转为对象存储即可
先定义返回对象
@Data
public class RuralWaterVoData {
private List<List<BuildscopeRuralwaterInfo>> data;
private String success;
}
定义要存储的对象
@Data
@EqualsAndHashCode(callSuper = false)
public class BuildscopeRuralwaterInfo implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.ASSIGN_UUID)
private String id;
@SerializedName("center_long")
private BigDecimal centerLong;
@SerializedName("center_lat")
private BigDecimal centerLat;
@SerializedName("cws_code")
private String cwsCode;
@SerializedName("cws_name")
private String cwsName;
}
循环请求根据分页参数 获取最新记录
for (int i = 1; i<= totalPage; i++) {
//设置请求分页参数
page.setPage_num(i);
String pageJson = gson.toJson(page);
String response = httpUtil.post("https://127.0.0.1", pageJson);
if (!resp.contains("errorCode")) {
//返回成功json字符串转对象
RuralWaterVoData ruralWaterVoData = gson.fromJson(response, RuralWaterVoData.class);
//获取返回对象list
List<BuildscopeRuralwaterInfo> buildscopeRuralwaterInfos = ruralWaterVoData.getData().get(1);
saveOrUpdateBatch(buildscopeRuralwaterInfos);
}
log.info("批量保存农村供水信息成功:" + i);
}

浙公网安备 33010602011771号