要將資料傳送到接受 POST請求的伺服器端腳本,例如“page.php”,請按照以下步驟操作:
請求初始化:
實例化一個URL 物件並開啟連線:
URL aaa = new URL("http://www.example.com/page.php"); URLConnection ccc = aaa.openConnection();
POST設定:
設定連線以允許 POST 資料提交:
ccc.setDoOutput(true); ccc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
查詢參數編碼:
請求轉換參數(例如id=10)到編碼查詢字串中:
String data = "id=" + URLEncoder.encode("10", "UTF-8");
資料傳輸:
將資料寫入連接的輸出流:
OutputStreamWriter wr = new OutputStreamWriter(ccc.getOutputStream()); wr.write(data); wr.flush();
回复處理:
獲取並處理服務器的響應:
BufferedReader br = new BufferedReader(new InputStreamReader(ccc.getInputStream())); String response = br.readLine();
更新的答案:
對於使用Apache HTTP 元件的Java程式設計師,最新的方法涉及HttpClients和HttpPost。參數作為 NameValuePair 列表傳遞,編碼為 UrlEncodedFormEntity,然後提交到伺服器:
HttpClient httpclient = HttpClients.createDefault(); HttpPost httppost = new HttpPost("http://www.a-domain.example/foo/"); List<NameValuePair> params = new ArrayList<>(2); params.add(new BasicNameValuePair("param-1", "12345")); params.add(new BasicNameValuePair("param-2", "Hello!")); httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); if (entity != null) { try (InputStream instream = entity.getContent()) { // Process the response here. } }
有關更多信息,請參閱 Apache HTTP 組件的文檔。
以上是如何在Java中發送HTTP POST請求?的詳細內容。更多資訊請關注PHP中文網其他相關文章!