接口调用:从第三方接口获取数据
1.环境: 系统框架:springboot,实现流程:controller→service
2.接口需求描述:
2. 代码示例
2.1 .Controller层
@PostMapping("/vehicleSync")
@PassToken
public BaseResponse VehicleSync(){
return carsyncService.VehicleSync();
}
2.2 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数据
Map<String, Object> postData = Maps.newHashMap();
postData.put("updateTime", time);
JSONObject rets = postData(apiUrl, JSONObject.toJSONString(postData));
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);
}
public static JSONObject postData(String urls, String jsonObject) {
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);
StringEntity stringEntity = new StringEntity(jsonObject, "UTF-8");
httpPost.setEntity(stringEntity);
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.addHeader("Content-Type", "application/json");
//执行请求操作,并拿到结果(同步阻塞)。(括号里的同步阻塞我也不知道什么意思,之后知道了再补上)
/* 设置参数到请求对象中 */
CloseableHttpResponse response = httpClient.execute(httpPost);
log.info(response.toString());
/* 获取结果实体 */
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);
}
}
3. 设置header/body参数请求
3.1 创建header参数
HttpPost httpPost = new HttpPost(urls);
httpPost.setEntity(stringEntity);
httpPost.addHeader("X-Build-Number", "100");
httpPost.addHeader("X-App-Version", "1.0.0");
httpPost.addHeader("X-Device-System-Info", "HWC");
httpPost.addHeader("Content-Type", "application/json");
CloseableHttpResponse response = httpClient.execute(httpPost);
3.2 创建body参数
HttpPost httpPost = new HttpPost(urls);
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");
JSONObject param = new JSONObject();
param.put("HttpHeader", inner.toString());
httpPost.setEntity( new StringEntity(param.toString()));
CloseableHttpResponse response = httpClient.execute(httpPost);
4. 拉取依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.4</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.11</version>
</dependency>
分类:
Java_基础篇
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具