Android網絡開發之HttpClient


Apache提供HttpClient,它對java.net中的類做了封裝和抽象,更適合在Android上開發應用。

HttpClient應用開發幾個類:

1. ClientConnectionManager是客戶端連接管理器的接口,

提供以下幾個抽象方法:

closeIdleConnections, 關閉空閑的連接

releaseConnection, 釋放一個連接

requestConnection, 請求一個新的連接

shutdown 關閉ClientConnectionManager並釋放資源

2. DefaultHttpClient是一個默認的Http客戶端,可以用來創建一個http連接。

HttpClient httpClient = new DefaultHttpClient();

3. HttpResponse是一個http連接響應

HttpResponse response = httpClient.execute(httpRequest);

if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)

 

//  示例代碼:HttpGet –> HttpClient –> HttpResponse

String url = “http://www.txrj.com/reg.jsp?name=jake”;

HttpGet request = new HttpGet(url);

HttpClient client = new DefaultHttpClient();

HttpResponse response = client.execute(request);

if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

  String data = EntityUtils.toString(response.getEntity());

}

 

// 示例代碼:HttpPost –> HttpClient –> HttpResponse

Post方式情況下,需要使用NameValuePair來保存要傳遞的參數,具體可以使用BasicNameValuePair,然后通過add方法添加到NameValuePair中。

String url = “http://www.txrj.com/reg.jsp”;

HttpPost request = new HttpPost(url);

// 添加參數

List<NameValuePair> params = new ArrayList<NameValuePair>();

params.add(new BasicNameValuePair(“name”,"jake”));

// 設置字符集

HttpEntity entity = new UrlEncodedFormEntity(params, “gb2312”);

request.setEntity(entity);

HttpClient client = new DefaultHttpClient();

HttpResponse response = client.execute(request);

if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

  String data = EntityUtils.toString(response.getEntity());

}


免責聲明!

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



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