zoukankan      html  css  js  c++  java
  • 接口调用:从第三方接口获取数据

    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>


     

  • 相关阅读:
    C语言寒假大作战01
    第十二次作业
    第十一次作业
    第十周作业
    第九次作业
    第8周作业
    第七次作业
    C语言I作业12—学期总结
    第一周作业
    C语言l博客作业02
  • 原文地址:https://www.cnblogs.com/bingsying/p/12506516.html
Copyright © 2011-2022 走看看