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>