接口调用:从第三方接口获取数据

1.环境: 系统框架:springboot,实现流程:controller→service

2.Controller层代码

@PostMapping("/vehicleSync")
@PassToken
public BaseResponse VehicleSync(){
return carsyncService.VehicleSync();
}

3.Service层代码

public BaseResponse VehicleSync() {

//定义接口路径
String apiUrl = "http://159.138.243.117:30000/app/get-vehilce-list/";
//接口参数
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = sdf.format(new Date());
//定义一个JSONObject类型的rets用于接收返回的JSON数据
JSONObject rets = postData(apiUrl);
if(ObjectUtils.isEmpty(rets)) {
return new BaseResponse(ResponseEnum.ERROR.getCode(), "Interface get parameter error");
}
//保存此条数据,框架是springboot,所以有Repository。不要生搬硬套代码
String Code = (String) rets.get("code");
if (ObjectUtils.isEmpty(Code)) {
//调用成功
JSONArray jsonArray = rets.getJSONArray("data");
//用一个集合接收返回的json数据中的data的值,遍历集合,取出数据
for (int i = 0, len = jsonArray.size(); i < len; i++) {
JSONObject jsonObject2 = (JSONObject) jsonArray.get(i);
VehicleSyncRequest request = new VehicleSyncRequest();
request.setLicensePlate(jsonObject2.get("licensePlate").toString());
request.setFuelType(jsonObject2.get("fuelType").toString());
request.setDeviceNo(jsonObject2.get("deviceNo").toString());
request.setSimNo(jsonObject2.get("simNo").toString());
request.setUpdateTime(jsonObject2.get("updateTime").toString());
request.setGuid(jsonObject2.get("guid").toString());
if (!isexistVehicle(request)){
log.error("Failed to add new vehicle", request.getLicensePlate());
continue;
}
}
} else {
return new BaseResponse(ResponseEnum.ERROR);
}
return new BaseResponse(ResponseEnum.SUCCESS);
}

//从接口获取数据 - 设置header参数
public static JSONObject postData(String urls){
    try {
/* 创建一个HttpClient最新版的实现类CloseableHttpClient */
CloseableHttpClient httpClient = HttpClients.createDefault();
//接口参数
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = sdf.format(new Date());
/* 创建post方法请求对象,并把拼接好的地址url赋值给它的请求参数urls */
HttpPost httpPost = new HttpPost(urls);
httpPost.addHeader("X-Build-Number","100");
httpPost.addHeader("X-App-Version","1.0.0");
httpPost.addHeader("X-Device-System-Info","HWC");
httpPost.addHeader("X-Device-Type","linux");
httpPost.addHeader("X-Language-Code","en");
httpPost.addHeader("X-Time-Stamp",time);
/* 设置报文头为Content-Type。具体格式看实际需求,我只知道如果请求的数据包为raw时,用Content-Type */
httpPost.setHeader("Content-Type", "application/json");
/* 设置参数到请求对象中 */
CloseableHttpResponse response = httpClient.execute(httpPost);
/* 获取结果实体 */
HttpEntity entity = response.getEntity();
/* 看返回状态是否正常,正常则把获取到的json字符串返回给调用者 */
int statue = response.getStatusLine().getStatusCode();
if (statue != HttpStatus.SC_OK) {
log.error("http connect fail:{}", response.getStatusLine());
}
//返回结果
String result = EntityUtils.toString(entity, "utf-8");
log.info(result);
return JSON.parseObject(result);
}catch (Exception e) {
log.error(e.toString());
return JSON.parseObject(null);
}
}
//从接口获取数据 - 设置body参数
public static JSONObject postData1(String urls){

try {
/* 创建一个HttpClient最新版的实现类CloseableHttpClient */
CloseableHttpClient httpClient = HttpClients.createDefault();
//接口参数
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = sdf.format(new Date());
/* 创建post方法请求对象,并把拼接好的地址url赋值给它的请求参数urls */
HttpPost httpPost = new HttpPost(urls);
/* 设置报文头为Content-Type。具体格式看实际需求,我只知道如果请求的数据包为raw时,用Content-Type */
httpPost.setHeader("Content-Type", "application/json");
//接口需要的参数
JSONObject inner = new JSONObject();
inner.put("X-Build-Number", "100");
inner.put("X-App-Version", "1.0.0");
inner.put("X-Device-System-Info", "HWC");
inner.put("X-Device-Type", "linux");
inner.put("X-Language-Code", "en");
inner.put("X-Time-Stamp", time);
JSONObject param = new JSONObject();
param.put("HttpHeader", inner.toString());
/* 设置参数到请求对象中 */
httpPost.setEntity( new StringEntity(param.toString()));
//执行请求操作,并拿到结果(同步阻塞)。(括号里的同步阻塞我也不知道什么意思,之后知道了再补上)
/* 设置参数到请求对象中 */
CloseableHttpResponse response = httpClient.execute(httpPost);
/* 获取结果实体 */
HttpEntity entity = response.getEntity();
/* 看返回状态是否正常,正常则把获取到的json字符串返回给调用者 */
int statue = response.getStatusLine().getStatusCode();
if (statue != HttpStatus.SC_OK) {
log.error("http connect fail:{}", response.getStatusLine());
}
//返回结果
String result = EntityUtils.toString(entity, "utf-8");
return JSON.parseObject(result);
}catch (Exception e) {
log.error(e.toString());
return JSON.parseObject(null);
}
}
上一篇:Broadcast


下一篇:ADB 操作手机的粘贴板