java 实现 Http的 Post 请求 用 Json 为参数
调用:
//_http_url_cdr为 //"http://10.10.10.243:15642/call/upload/ctiCdrUpload" //eventJson 为 //{"callid":"1635822668.528","callto":"6700(1008)","pincode":"","srctrunkname":"MNWG","status":"ANSWERED"} //Http请求 httpPost(_http_url_cdr,eventJson);
参数手动生成函数
public static void httpPost(String url,String eventJson){ //发送请求的URL //String url = "http://10.10.10.243:15642/call/upload/ctiCdrUpload"; logger.debug("httpPost() 准备HttpPost请求! " + url + " " + ""); //请求内容 示例 /* { "event": "NewCdr", "callid": "1627349862.433", "timestart": "2021-07-27 09:37:42", "callfrom": "1008", "callto": "1009" }*/ //请求内容 示例 手动生成 /* JSONObject jsonParam = new JSONObject(); jsonParam.put("event","NewCdr"); jsonParam.put("callid","1627349862.433"); jsonParam.put("timestart","2021-07-27 09:37:42"); jsonParam.put("callfrom","1008"); jsonParam.put("callto","1009"); jsonParam.put("callduraction","16"); jsonParam.put("talkduraction","11"); jsonParam.put("srctrunkname",""); jsonParam.put("dsttrcunkname",""); */ //将字符串转化成JSONObject JSONObject jsonParam= JSON.parseObject(eventJson); logger.debug("httpPost() HttpPost请求参数: " + jsonParam.toJSONString() + " " + ""); //发送Http Post请求 JSONObject jsonResult=httpPostSendRequest(url,jsonParam); logger.debug("httpPost() HttpPost请求结果: " + jsonResult.toString() + " " + ""); }
java通用 Http Post 请求 方法
public static JSONObject httpPostSendRequest(String url,JSONObject param){ //定义接收数据 JSONObject result = new JSONObject(); HttpPost httpPost = new HttpPost(url); CloseableHttpClient client = HttpClients.createDefault(); //请求参数转JOSN字符串 StringEntity entity = new StringEntity(param.toJSONString(), "UTF-8"); entity.setContentEncoding("UTF-8"); entity.setContentType("application/json"); httpPost.setEntity(entity); try { HttpResponse response = client.execute(httpPost); if (response.getStatusLine().getStatusCode() == 200) { result = JSON.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8")); } } catch (Exception e) { e.printStackTrace(); //result.put("error", "连接错误!"); logger.error("httpPostSendRequest() HttpPost " + "=======连接错误======="); } return result; }
感谢:huatian007
https://www.cnblogs.com/huatian007/p/16484425.html