歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android 網絡操作常用的兩個類

Android 網絡操作常用的兩個類

日期:2017/3/1 9:57:10   编辑:Linux編程

Android SDK集成了Apache HttpClient模塊。要注意的是,這裡的Apache HttpClient模塊是HttpClient 4.0(org.apache.http.*),而不是常見的 Jakarta Commons HttpClient 3.x(org.apache.commons.httpclient.*)。

HttpClient常用HttpGet和HttpPost這兩個類,分別對應Get方式和Post方式。

無論是使用HttpGet,還是使用HttpPost,都必須通過如下3步來訪問HTTP資源。

1.創建HttpGet或HttpPost對象,將要請求的URL通過構造方法傳入HttpGet或HttpPost對象。

2.使用DefaultHttpClient類的execute方法發送HTTP GET或HTTP POST請求,並返回HttpResponse對象。

3.通過HttpResponse接口的getEntity方法返回響應信息,並進行相應的處理。

如果使用HttpPost方法提交HTTP POST請求,則需要使用HttpPost類的setEntity方法設置請求參數。參數則必須用NameValuePair[]數組存儲。

下面給出一些實例:

Get方式:

// HttpGet方式請求
public static void requestByHttpGet() throws Exception {
String path = "https://reg.163.com/logins.jsp?id=helloworld&pwd=android";
// 新建HttpGet對象
HttpGet httpGet = new HttpGet(path);
// 獲取HttpClient對象
HttpClient httpClient = new DefaultHttpClient();
// 獲取HttpResponse實例
HttpResponse httpResp = httpClient.execute(httpGet);
// 判斷是夠請求成功
if (httpResp.getStatusLine().getStatusCode() == HTTP_200) {
// 獲取返回的數據
String result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
Log.i(TAG_HTTPGET, "HttpGet方式請求成功,返回數據如下:");
Log.i(TAG_HTTPGET, result);
} else {
Log.i(TAG_HTTPGET, "HttpGet方式請求失敗");
}
}

public String doGet()
{
String uriAPI = "http://XXXXX?str=I+am+get+String";
String result= "";
// HttpGet httpRequst = new HttpGet(URI uri);
// HttpGet httpRequst = new HttpGet(String uri);
// 創建HttpGet或HttpPost對象,將要請求的URL通過構造方法傳入HttpGet或HttpPost對象。
HttpGet httpRequst = new HttpGet(uriAPI);

// new DefaultHttpClient().execute(HttpUriRequst requst);
try {
//使用DefaultHttpClient類的execute方法發送HTTP GET請求,並返回HttpResponse對象。
HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequst);//其中HttpGet是HttpUriRequst的子類
if(httpResponse.getStatusLine().getStatusCode() == 200)
{
HttpEntity httpEntity = httpResponse.getEntity();
result = EntityUtils.toString(httpEntity);//取出應答字符串
// 一般來說都要刪除多余的字符
result.replaceAll("\r", "");//去掉返回結果中的"\r"字符,否則會在結果字符串後面顯示一個小方格
}
else
httpRequst.abort();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
result = e.getMessage().toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
result = e.getMessage().toString();
}
return result;
}

Copyright © Linux教程網 All Rights Reserved