java笔记_2_接口调用

post接口

//import lombok.extern.slf4j.Slf4j; 用于日志输出
//@Slf4j

  public JSONObject extractingAnslysisTask(JSONObject paramJson) {
    //获取文件路径
    String fileStr = paramJson.getString("fileStr");
    //接口路径
    String url = "http://xxxxxx/xxxx";
    JSONObject resultJson = null;
   //---入参类型一
    HashMap<String, Object> paramMap = new HashMap<>();
    paramMap.put("file", FileUtil.file(fileStr));//文件类入参
    paramMap.put("index1", "xxx");//字符串类入参
    paramMap.put("index2", 1);//数值类入参
  //---入参类型二
    //JSONObject param = new JSONObject(); 
    //param.put("file_id", req.getFileId()); 
    //param.put("exclude_opposite_account", req.getExcludeOppositeAccount()); 
    //param.put("top5_income", req.getTop5Income()); 
    //param.put("sales_revenue", req.getSalesRevenue()); 


    try {
        //没有Authorization可不加header()
        //---调用方法一
        String result = HttpRequest.post(url).header("Authorization",Authorization).form(paramMap).execute().body();
        //---调用方法二(对应入参类型二)
        //String result = HttpRequest.post(url).header("Authorization",Authorization).body(param.toJSONString()).execute().body();

        log.info("result ==> " + result);
        //将结果String转为JsonObject
        resultJson = JSON.parseObject(result);
        //根据不同的返回结果进行判断
        if (resultJson.getInteger("status") != 200) {
            log.info("接口调用失败:" + resultJson.getString("message"));
        }
    } catch(Exception e) {
        log.info("接口异常:" + e.getMessage());
    }
    return resultJson;
}

get接口

//import lombok.extern.slf4j.Slf4j; 用于日志输出
//@Slf4j
public JSONObject parseResult(JSONObject paramJson) {
        String index= paramJson.getString("index");
        String url = "http://xxxxxxx";
        JSONObject resultJson = null;

        JSONObject param = new JSONObject();
        param.put("index",index);//入参

        try {
            //没有Authorization可不加header()
            String result = HttpRequest.get(url).header("Authorization",Authorization).body(JSON.toJSONString(param)).execute().body();
            log.info("result ==> " + result);

            resultJson = JSON.parseObject(result);
            if (resultJson.getInteger("status") != 200) {
                log.info("接口调用失败:" + resultJson.getString("message"));
            }
        } catch(Exception e) {
            log.info("接口异常:" + e.getMessage());
        }
        return resultJson;
    }

 

posted @ 2022-08-03 12:11  LuLuYaa  阅读(23)  评论(0编辑  收藏  举报