HttpURLConnection發送請求

來源:互聯網
上載者:User

標籤:字元   透明   har   cal   demo   .net   調用   put   urlencode   

每個 HttpURLConnection 執行個體都可用於產生單個請求,但是其他執行個體可以透明地共用串連到 HTTP 伺服器的基礎網路。請求後在 HttpURLConnection 的 InputStream 或 OutputStream 上調用 close() 方法可以釋放與此執行個體關聯的網路資源,但對共用的持久串連沒有任何影響。如果在調用 disconnect() 時持久串連空閑,則可能關閉基礎通訊端。JAVA使用HttpURLConnection發送POST資料是依靠OutputStream流的形式發送

package com.newflypig.demo;/** * 使用jdk內建的HttpURLConnection向URL發送POST請求並輸出響應結果 * 參數使用流傳遞,並且寫入程式碼為字串"name=XXX"的格式 */import java.io.BufferedReader;import java.io.DataOutputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;import java.net.URLEncoder;public class SendPostDemo {  public static void main(String[] args) throws Exception{    String urlPath = new String("http://localhost:8080/Test1/HelloWorld");     //String urlPath = new String("http://localhost:8080/Test1/HelloWorld?name=丁丁".getBytes("UTF-8"));    String param="name="+URLEncoder.encode("丁丁","UTF-8");    //建立串連    URL url=new URL(urlPath);    HttpURLConnection httpConn=(HttpURLConnection)url.openConnection();    //設定參數    httpConn.setDoOutput(true);   //需要輸出    httpConn.setDoInput(true);   //需要輸入    httpConn.setUseCaches(false);  //不允許緩衝    httpConn.setRequestMethod("POST");   //設定POST方式串連    //佈建要求屬性    httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");    httpConn.setRequestProperty("Connection", "Keep-Alive");// 維持長串連    httpConn.setRequestProperty("Charset", "UTF-8");    //串連,也可以不用明文connect,使用下面的httpConn.getOutputStream()會自動connect    httpConn.connect();    //建立輸入資料流,向指向的URL傳入參數    DataOutputStream dos=new DataOutputStream(httpConn.getOutputStream());    dos.writeBytes(param);    dos.flush();    dos.close();    //獲得響應狀態    int resultCode=httpConn.getResponseCode();    if(HttpURLConnection.HTTP_OK==resultCode){      StringBuffer sb=new StringBuffer();      String readLine=new String();      BufferedReader responseReader=new BufferedReader(new InputStreamReader(httpConn.getInputStream(),"UTF-8"));      while((readLine=responseReader.readLine())!=null){        sb.append(readLine).append("\n");      }      responseReader.close();      System.out.println(sb.toString());    }   }}

  

HttpURLConnection發送請求

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.