後臺發起post請求,並返回請求結果
阿新 • • 發佈:2018-11-09
1.感謝
https://blog.csdn.net/Java_Long_Asus/article/details/82906135
2.程式碼
/** * 向指定的 URL傳送遠端POST方法的請求 * @param url傳送請求的 URL * @param json請求引數, * @return 所代表遠端資源的響應結果 */ public static JSONObject sendPost(String url, JSON json) { PrintWriter out = null; BufferedReader in = null; JSONObject jsonObject = null; String result = ""; try { URL realUrl = new URL(url); // 開啟和URL之間的連線 HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection(); // 設定通用的請求屬性 conn.setRequestMethod("POST"); // 傳送POST請求必須設定下面的屬性 conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); //設定請求屬性 conn.setRequestProperty("Content-Type", "application/json; charset=utf-8"); conn.connect(); // 獲取URLConnection物件對應的輸出流 out = new PrintWriter(conn.getOutputStream()); // 傳送請求引數 out.print(JSON.toJSONString(json)); // flush輸出流的緩衝 out.flush(); // 定義BufferedReader輸入流來讀取URL的響應 in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = ""; while ((line = in.readLine()) != null) { result += line; } //將返回結果轉換為字串 jsonObject = JSONObject.parseObject(result); } catch (Exception e) { throw new RuntimeException("遠端通路異常"+e.toString()); } // 使用finally塊來關閉輸出流、輸入流 finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return jsonObject; }