Java用apache的HttpClient發送Post請求__Java

來源:互聯網
上載者:User

原文地址:http://www.pocketdigi.com/20110521/294.html


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")


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.