1. 程式人生 > >Java用apache的HttpClient傳送Post請求

Java用apache的HttpClient傳送Post請求

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
/**
*JDK預設沒有org.apache.http包,需要先去http://hc.apache.org/downloads.cgi下載
*下載HttpClient,解壓,在Eclipse中匯入所有JAR
*/
public class TT {
/**
* @param args
* @throws UnsupportedEncodingException
* 這個例子為了簡單點,沒有捕捉異常,直接在程式入口加了異常丟擲宣告
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
String url="http://localhost/newspaper/test/1.php";
//POST的URL
HttpPost httppost=new HttpPost(url);
//建立HttpPost物件
List<NameValuePair> params=new ArrayList<NameValuePair>();
//建立一個NameValuePair陣列,用於儲存欲傳送的引數
params.add(new BasicNameValuePair("pwd","2544"));
//新增引數
httppost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
//設定編碼
HttpResponse response=new DefaultHttpClient().execute(httppost);
//傳送Post,並返回一個HttpResponse物件
if(response.getStatusLine().getStatusCode()==200){//如果狀態碼為200,就是正常返回
String result=EntityUtils.toString(response.getEntity());
//得到返回的字串
System.out.println(result);
//列印輸出
}
}
}

處理亂碼,對取得的result字串作下轉換,

result=new String(result.getBytes("ISO-8859-1"),"GBK")