1. 程式人生 > >JAVA HttpURLConnection Post方式提交傳遞引數

JAVA HttpURLConnection Post方式提交傳遞引數

public class HttpURLConnectionPost {

 /**
  * @param args
  * @throws IOException
  */
 public static void main(String[] args) throws IOException {
  readContentFromPost();
 }
 public static void readContentFromPost() throws IOException {
        // Post請求的url,與get不同的是不需要帶引數
        URL postUrl = new URL("http://www.xxxxxxx.com");
        // 開啟連線
        HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();     
        // 設定是否向connection輸出,因為這個是post請求,引數要放在
        // http正文內,因此需要設為true
        connection.setDoOutput(true);
        // Read from the connection. Default is true.
        connection.setDoInput(true);
        // 預設是 GET方式
        connection.setRequestMethod("POST");      
        // Post 請求不能使用快取
        connection.setUseCaches(false);  
           //設定本次連線是否自動重定向 
        connection.setInstanceFollowRedirects(true);      
        // 配置本次連線的Content-type,配置為application/x-www-form-urlencoded的
        // 意思是正文是urlencoded編碼過的form引數
        connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
        // 連線,從postUrl.openConnection()至此的配置必須要在connect之前完成,
        // 要注意的是connection.getOutputStream會隱含的進行connect。
        connection.connect();
        DataOutputStream out = new DataOutputStream(connection
                .getOutputStream());
        // 正文,正文內容其實跟get的URL中 '? '後的引數字串一致
        String content = "欄位名=" + URLEncoder.encode("字串值", "編碼");
        // DataOutputStream.writeBytes將字串中的16位的unicode字元以8位的字元形式寫到流裡面
        out.writeBytes(content);
        //流用完記得關
        out.flush();
        out.close();
        //獲取響應
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null){
            System.out.println(line);
        }
        reader.close();
        //該乾的都幹完了,記得把連線斷了
        connection.disconnect();
}

}