轉自: http://wang09si.blog.163.com/blog/static/1701718042013631104658130/java
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;app
public class HttpURLConnectionPost {post
/**
* @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();
}url
}
在接收端,這樣獲取參數:
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")); spa