java模拟post请求发送json,用两种方式实现,第一种是HttpURLConnection发送post请求,第二种是使用httpclient模拟post请求。java
方法一:json
public static String sendPost(String url_param, String param) { String result = "";// 返回的结果 BufferedReader in = null;// 读取响应输入流 // PrintWriter out = null; try { // 建立URL对象 URL url = new URL(url_param); // 打开URL链接 java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) url .openConnection(); // 设置属性 httpConn.setRequestProperty("Content-Type", "application/json"); // 设置POST方式 httpConn.setDoInput(true); httpConn.setDoOutput(true); httpConn.setRequestMethod("POST"); httpConn.setUseCaches(false); httpConn.setInstanceFollowRedirects(true); // 获取HttpURLConnection对象对应的输出流 DataOutputStream out = new DataOutputStream(httpConn.getOutputStream()); out.write(param.getBytes("utf-8")); // flush输出流的缓冲 out.flush(); out.close(); // 定义BufferedReader输入流来读取URL的响应,设置编码方式 in = new BufferedReader(new InputStreamReader(httpConn .getInputStream(), "UTF-8")); String line; // 读取返回的内容 while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { e.printStackTrace(); } finally { try { /* if (out != null) { out.close(); } */ if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; }
方法二:app
public String sendPost(String url, String data) { String response = null; log.info("url: " + url); log.info("request: " + data); try { CloseableHttpClient httpclient = null; CloseableHttpResponse httpresponse = null; try { httpclient = HttpClients.createDefault(); HttpPost httppost = new HttpPost(url); StringEntity stringentity = new StringEntity(data, ContentType.create("text/json", "UTF-8")); httppost.setEntity(stringentity); httpresponse = httpclient.execute(httppost); response = EntityUtils .toString(httpresponse.getEntity()); log.info("response: " + response); } finally { if (httpclient != null) { httpclient.close(); } if (httpresponse != null) { httpresponse.close(); } } } catch (Exception e) { e.printStackTrace(); } return response; }