/**
* post请求以及参数是json
* @param url
* @param jsonParams
* @return
*/
public static JSONObject doPostForJson(String url, String jsonParams, String token) {
CloseableHttpClient httpClient = HttpClients.createDefault();
JSONObject jsonObject = null;
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().
setConnectTimeout(180 * 1000).setConnectionRequestTimeout(180 * 1000)
.setSocketTimeout(180 * 1000).setRedirectsEnabled(true).build();
httpPost.setConfig(requestConfig);
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Authorization", token);
try {
httpPost.setEntity(new StringEntity(jsonParams, ContentType.create("application/json", "utf-8")));
System.out.println("request parameters" + EntityUtils.toString(httpPost.getEntity()));
HttpResponse response = httpClient.execute(httpPost);
if (response != null && response.getStatusLine().getStatusCode() == 200) {
String result = EntityUtils.toString(response.getEntity());
jsonObject = JSONObject.parseObject(result);
return jsonObject;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != httpClient) {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return jsonObject;
}
}
调用实例:
private List<GoalResultVo> getGoalList(Long id) {
GoalRequestVo vo = new GoalRequestVo();
JSONObject condition = new JSONObject();
condition.put("year", 2020);
condition.put("goalModelId", id);
condition.put("goalPeriod", 3);
condition.put("isSum", false);
condition.put("done", true);
vo.setCondition(condition);
String jsonParam = JSON.toJSONString(vo);
String token = tokenUtil.getAccessToken();
JSONObject jsonObject = HttpClientUtil.doPostForJson(goalUrl, jsonParam, token);
JSONObject data = (JSONObject) jsonObject.get("data");
JSONArray goalProDetails = (JSONArray) data.get("goalProDetails");
return JSONObject.parseArray(goalProDetails.toJSONString(), GoalResultVo.class);
}
注意: 平时代码中,可用使用 JSONObject 代替Map来存储对象更方便一些;