Java後端發出post請求帶參數並接收返回的json

來源:互聯網
上載者:User

標籤:null   utf-8   https   word   trace   擷取   blog   writer   out   

核心代碼:

參數格式:

“key1=value1&key2=value2”

/**
*  sendUrl    (遠程請求的URL)
*  param    (遠程請求參數)
*  JSONObject    (遠程請求返回的JSON)
*/
private
JSONObject sendPostUrl(String url, String param){ PrintWriter out = null; BufferedReader in = null; JSONObject jsonObject = null; String result = ""; try { URL realUrl = new URL(url); // 開啟和URL之間的串連 URLConnection conn = realUrl.openConnection(); // 發送POST請求必須設定如下兩行 conn.setDoOutput(true); conn.setDoInput(true); // 擷取URLConnection對象對應的輸出資料流(佈建要求編碼為UTF-8) out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8")); // 發送請求參數 out.print(param); // flush輸出資料流的緩衝 out.flush(); // 擷取請求返回資料(設定返回資料編碼為UTF-8) in = new BufferedReader( new InputStreamReader(conn.getInputStream(), "UTF-8")); String line; while ((line = in.readLine()) != null) { result += line; } jsonObject = JSONObject.fromObject(result); System.out.println(jsonObject); } catch (IOException e) { e.printStackTrace(); } finally{ try{ if(out!=null){ out.close(); } if(in!=null){ in.close(); } } catch(IOException ex){ ex.printStackTrace(); } } return jsonObject; }
調用方法:
public JSONObject send(String username, String password){        String params = "username=" + username+ "&password=" + password;        JSONObject jsonObject = sendPostUrl("https://www.ysy7.com/login/", params);        return jsonObject;    }

 

Java後端發出post請求帶參數並接收返回的json

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.