HttpUtils 网络请求工具类

Siona

HttpUtils 网络请求工具类

有问题,用的时候挺难用的,参考 Hutool 工具类进行修改吧‼️️ Http客户端工具类-HttpUtilopen in new window

见 assets/code/HttpUtils.java


使用

doNewGet

String path = hikConfig.getPath();

Map<String, String> querys = new HashMap<>();
querys.put("indexCode", "root000000");
querys.put("pageNo", "1");
querys.put("pageSize", "1000");

String result;
try {
    result = HttpUtils.doNewGet(hikConfig.getHost(), path, "GET", null, querys);

    if (StringUtils.isEmpty(result)){
        throw new ApiException("同步数据源失败!");
    }
} catch (Exception e) {
    e.printStackTrace();
    throw new ApiException("同步数据源失败!");
}

doIsNewGet

String path = diaoZhenConfig.getPath() + ApiAddressConstant.GET_WASTE_GAS_REAL_DATA;

Map<String, String> querys = new HashMap<>();
querys.put("stationCode", stationCode);

SortedMap<String, String> xmlMap = new TreeMap<>();
try {
    InputStream inputStream = HttpUtils.doIsNewGet(diaoZhenConfig.getHost(), path, "GET", null, querys);
    xmlMap = XmlUtils.parseXml(inputStream);

} catch (Exception e) {
    e.printStackTrace();
    throw new ApiException("获取废气-实时数据失败!");
}

Map<String, Object> map = new HashMap<>();
map.put("type", "gas");

JSONArray gasArray = JSON.parseArray(xmlMap.get("data"));  // 将 data 取出进行阈值比对,若超过阈值则状态为"报警"

doIsNewGet


doNewPost

ServletContext application = webApplicationContext.getServletContext();
JSONObject jsonObject = new JSONObject();
jsonObject.put("key", key);
jsonObject.put("secret", secret);

Map<String, String> headers = new HashMap<>();
headers.put("content-type", "application/json; charset=utf-8");

String returnData = null;
try {
    returnData = HttpUtils.doNewPost(url, "/api/v1/sysAuth/getToken", "POST", headers, null, jsonObject.toJSONString());
    if (returnData != null) {
        JSONObject result = JSONObject.parseObject(returnData);
        JSONObject json = result.getJSONObject("data");
        if (json.containsKey("access_token")) {
            if (json.get("access_token") != null && !json.get("access_token").equals("")) {
                // expires_in 返回的是秒
                application.setAttribute("tokenMap", new AuthAccessToken(json.get("access_token").toString(),
                        System.currentTimeMillis() + Integer.parseInt(json.get("expires_in").toString()) * 1000));
                log.info("access_token: {}", json.toString());
                return json.get("access_token").toString();
            }
        } else {
            log.info("统一认证中心报错:{}", returnData);
        }
    }
} catch (Exception e) {
    e.printStackTrace();
    throw new ApiException("获取TOKEN失败");
}
return null;
Last Updated 3/2/2024, 4:00:59 PM