java實現傳送post請求
阿新 • • 發佈:2019-01-05
post、get請求一般出現在前端呼叫後端介面的時候,現在如果希望java程式碼去呼叫controller介面,比如在job定時器中,達到某一條件需要返回給前端一條提示訊息(如訂單30分鐘內未付款,已被自動取消),而前端只能調controler介面,所以這時可以用job去調controller介面,在這個controller接口裡面返回資訊給前端。
* @param url:請求url * @param content: 請求體(引數) * @return errorStr:錯誤資訊;status:狀態碼,response:返回資料 */ public Map<String, Object> request(String url, String content) { Map<String, Object> result = new HashMap<String, Object>(); String errorStr = ""; String status = ""; String response = ""; PrintWriter out = null; BufferedReader in = null; try { URL realUrl = new URL(url); // 開啟和URL之間的連線 URLConnection conn = realUrl.openConnection(); HttpURLConnection httpUrlConnection = (HttpURLConnection) conn; // 設定請求屬性 httpUrlConnection.setRequestProperty("Content-Type", "application/json"); httpUrlConnection.setRequestProperty("x-adviewrtb-version", "2.1"); // 傳送POST請求必須設定如下兩行 httpUrlConnection.setDoOutput(true); httpUrlConnection.setDoInput(true); // 獲取URLConnection物件對應的輸出流 out = new PrintWriter(httpUrlConnection.getOutputStream()); // 傳送請求引數 out.write(content); // flush輸出流的緩衝 out.flush(); httpUrlConnection.connect(); // 定義BufferedReader輸入流來讀取URL的響應 in = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream())); String line; while ((line = in.readLine()) != null) { response += line; } status = new Integer(httpUrlConnection.getResponseCode()).toString(); } catch (Exception e) { System.out.println("傳送 POST 請求出現異常!" + e); errorStr = e.getMessage(); } // 使用finally塊來關閉輸出流、輸入流 finally { try { if (out != null) { out.close();} if (in != null) {in.close();} } catch (Exception ex) { ex.printStackTrace(); } } result.put("errorStr", errorStr); result.put("response", response); result.put("status", status); return result; }