Android SDK集成了Apache HttpClient模塊。要注意的是,這里的Apache HttpClient模塊是 HttpClient 4.0(org.apache.http.*),而不是常見(jiàn)的Jakarta Commons HttpClient 3.x (org.apache.commons.httpclient.*)。 HttpClient常用HttpGet和HttpPost這兩個(gè)類,分別對(duì)應(yīng)Get方式和Post方式。
無(wú)論是使用HttpGet,還是使用HttpPost,都必須通過(guò)如下3步來(lái)訪問(wèn)HTTP資源。
1.創(chuàng)建HttpGet或HttpPost對(duì)象,將要請(qǐng)求的URL通過(guò)構(gòu)造方法傳入HttpGet或HttpPost對(duì)象。 2.使用DefaultHttpClient類的execute方法發(fā)送HTTP GET或HTTP POST請(qǐng)求,并返回HttpResponse對(duì)象。 3.通過(guò)HttpResponse接口的getEntity方法返回響應(yīng)信息,并進(jìn)行相應(yīng)的處理。 如果使用HttpPost方法提交HTTP POST請(qǐng)求,則需要使用HttpPost類的setEntity方法設(shè)置請(qǐng)求參數(shù)。參數(shù)則必須用NameValuePair[]數(shù)組存儲(chǔ)。 [java] view plaincopy - public String doGet()
- {
- String uriAPI = "http://XXXXX?str=I+am+get+String";
- String result= "";
-
-
-
- HttpGet httpRequst = new HttpGet(uriAPI);
-
-
- try {
-
- HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequst);
- if(httpResponse.getStatusLine().getStatusCode() == 200)
- {
- HttpEntity httpEntity = httpResponse.getEntity();
- result = EntityUtils.toString(httpEntity);
-
- result.replaceAll("\r", "");
- }
- else
- httpRequst.abort();
- } catch (ClientProtocolException e) {
-
- e.printStackTrace();
- result = e.getMessage().toString();
- } catch (IOException e) {
-
- e.printStackTrace();
- result = e.getMessage().toString();
- }
- return result;
- }
如果使用HttpPost方法提交HTTP POST請(qǐng)求,則需要使用HttpPost類的setEntity方法設(shè)置請(qǐng)求參數(shù)。參數(shù)則必須用NameValuePair[]數(shù)組存儲(chǔ)。 - public String doPost()
- {
- String uriAPI = "http://XXXXXX";//Post方式?jīng)]有參數(shù)在這里
- String result = "";
- HttpPost httpRequst = new HttpPost(uriAPI);
-
- List <NameValuePair> params = new ArrayList<NameValuePair>();
- params.add(new BasicNameValuePair("str", "I am Post String"));
-
- try {
- httpRequst.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
- HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequst);
- if(httpResponse.getStatusLine().getStatusCode() == 200)
- {
- HttpEntity httpEntity = httpResponse.getEntity();
- result = EntityUtils.toString(httpEntity);
- }
- } catch (UnsupportedEncodingException e) {
-
- e.printStackTrace();
- result = e.getMessage().toString();
- }
- catch (ClientProtocolException e) {
-
- e.printStackTrace();
- result = e.getMessage().toString();
- }
- catch (IOException e) {
-
- e.printStackTrace();
- result = e.getMessage().toString();
- }
- return result;
- }
以發(fā)送連接請(qǐng)求時(shí),需要設(shè)置鏈接超時(shí)和請(qǐng)求超時(shí)等參數(shù),否則會(huì)長(zhǎng)期停止或者崩潰。 - HttpParams httpParameters = new BasicHttpParams();
- HttpConnectionParams.setConnectionTimeout(httpParameters, 10*1000);
- HttpConnectionParams.setSoTimeout(httpParameters, 10*1000);
- HttpConnectionParams.setSocketBufferSize(params, 8192);
- HttpClient httpclient = new DefaultHttpClient(httpParameters);
-
-
-
- 由于是聯(lián)網(wǎng),在AndroidManifest.xml中添加網(wǎng)絡(luò)連接的權(quán)限
- <uses-permission android:name="android.permission.INTERNET"/>
|