public String sendPostRequest(String url,Map<String,String> parameters){
// Post請求的url,與get不同的是不需要帶參數
String result="";
try {
URL postUrl = new URL(url);
// 加入代理start
Properties systemProperties =System.getProperties();
systemProperties.setProperty("http.proxyHost",proxyHost);
systemProperties.setProperty("http.proxyPort",String.valueOf(proxyPort));
// 加入代理end
// 打開連接
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; charset=UTF-8");
// 連接,從postUrl.openConnection()至此的配置必須要在connect之前完成,
// 要注意的是connection.getOutputStream會隱含的進行connect。
connection.connect();
DataOutputStream out = new DataOutputStream(connection
.getOutputStream());
// 正文,正文內容其實跟get的URL中 '? '後的參數字符串一致
String content = "name=11&pas=";
// DataOutputStream.writeBytes將字符串中的16位的unicode字符以8位的字符形式寫到流裏面
if(null != parameters && parameters.size()>0){
for(Map.Entry<String,String> entry : parameters.entrySet()){
content +="&"+entry.getKey()+"="+URLEncoder.encode(entry.getValue(), "utf-8");
}
}
out.writeBytes(content.replaceFirst("&", ""));
//流用完記得關
out.flush();
//去掉代理start
System.getProperties().remove("http.proxyHost");
System.getProperties().remove("http.proxyPort");
//去掉代理end
out.close();
//獲取響應
//獲取請求的資源
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
result =br.readLine();
br.close();
//該乾的都幹完了,記得把連接斷了
connection.disconnect();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
return result;
}