当前位置: 首页 > >

Java代码:CloseableHttpClient HttpPost 调用外部接口(模拟表单传参或JSON传参)

发布时间:

public void finishNotice(String url ,Map paraMap){
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
Integer status=null;
String msg="";
String problemCode="";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
// 创建参数列表
if (paraMap != null) {
// List paramList = new ArrayList<>();
for (String key : paraMap.keySet()) {
// paramList.add(new BasicNameValuePair(key, paraMap.get(key)));
if(key.equals("problemCode")){
problemCode = paraMap.get(key);
}
}
// 模拟表单
// UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
// httpPost.setEntity(entity);
//json格式传参
String param=JSON.toJSONString(paraMap);
httpPost.setEntity(new StringEntity(param));
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
JSONObject jsonObject = JSON.parseObject(resultString);
status = (Integer) jsonObject.get("status");
msg= (String) jsonObject.get("msg");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}



友情链接: year2525网 工作范文网 QS-ISP 138资料网 528200 工作范文网 baothai 表格模版