JAVA HttpURLConnection Post方式提交傳遞參數


原文:http://wang09si.blog.163.com/blog/static/1701718042013631104658130/

package wzq.j2se;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

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.wangzhiqiang87.cn");
        // 打開連接
        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參數,下面我們可以看到我們對正文內容使用URLEncoder.encode
        // 進行編碼
        connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
        // 連接,從postUrl.openConnection()至此的配置必須要在connect之前完成,
        // 要注意的是connection.getOutputStream會隱含的進行connect。
        connection.connect();
        DataOutputStream out = new DataOutputStream(connection
                .getOutputStream());
        // The URL-encoded contend
        // 正文,正文內容其實跟get的URL中 '? '后的參數字符串一致
        String content = "account=" + URLEncoder.encode("一個大肥人", "UTF-8");
        content +="&pswd="+URLEncoder.encode("兩個個大肥人", "UTF-8");;
        // 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();
}

}

在接收端,這樣獲取參數:
String name = request.getParameter("account");
String pswd = request.getParameter("pswd");
 
 System.out.println(new String(name.getBytes("iso-8859-1"),"UTF-8"));
 System.out.println(new String(pswd.getBytes("iso-8859-1"),"UTF-8"));


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM