一起學android之Apache介面(17)

來源:互聯網
上載者:User

標籤:http   android   網路   android網路編程   httpclient   

Apache HttpClient是一個開源項目,為用戶端的HTTP編程提供高效、最新、功能豐富的工具包支援。


在Apache HttpClient庫中,我們常用的對網路連接有用的包主要有以下幾類:

-org.apache.http.HttpResponse

-org.apache.http.client.HttpClient

-org.apache.http.client.methods.HttpGet

-org.apache.http.impl.client.DefaulfHttpClient

HttpClient httpclient=new DefaultHttpClient();


如果是從伺服器檢索資訊,需要使用HttpGet類的構造器,例如以下代碼:

<span style="font-size:18px;">HttpGet request=new HttpGet("http://google.com");</span>
然後用HttpClient類的execut()方法中的HttpGet對象來檢索HttpResponse對象,例如下面代碼:

<span style="font-size:18px;">HttpResponse response=client.execute(request);</span>
最後讀取已檢索的響應,例如下面代碼:

<span style="font-size:18px;">BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));String line="";while ((line=rd.readLine())!=null) {System.out.println(line);}</span>


在Android系統中,可以採用HttpPost和HttpGet來封裝Post請求和Get請求,然後使用HttpClient的execut()方法發送Post或者Get請求並返回伺服器的響應資料。

Apache連網的基本流程如下:

1、設定串連和讀取逾時時間,並建立HttpClient對象,例如下面代碼:

<span style="font-size:18px;">HttpParams httpParames=new BasicHttpParams();HttpConnectionParams.setConnectionTimeout(httpParames, 2000);HttpConnectionParams.setSoTimeout(httpParames, 2000);HttpClient httpClient=new DefaultHttpClient(httpParames);</span>

2、實現Get請求,例如下面代碼:

<span style="font-size:18px;">HttpGet get = new HttpGet(uri);if (headers != null) {Set<String> setHead = headers.keySet();Iterator<String> iteratorHead = setHead.iterator();while (iteratorHead.hasNext()) {String headerName = iteratorHead.next();String headerValue = (String) headers.get(headerName);get.setHeader(headerName, headerValue);}}response = httpClient.execute(get);</span>
3、實現Post發送請求處理,例如下面代碼:

<span style="font-size:18px;">HttpPost post = new HttpPost(uri);Set<String> setHead = headers.keySet();Iterator<String> iteratorHead = setHead.iterator();while (iteratorHead.hasNext()) {String headName = iteratorHead.next();String headValue = (String) headers.get(headName);post.setHeader(headName, headValue);}ContentProducer cp = new ContentProducer() {@Overridepublic void writeTo(OutputStream outstream) throws IOException {Writer writer = new OutputStreamWriter(outstream, "UTF-8");writer.write(requestBody);writer.flush();writer.close();}};HttpEntity entity = new EntityTemplate(cp);post.setEntity(entity);response = httpClient.execute(post);</span>
通常的Http實體需要在執行內容的時候動態產生的。HttpClient的提供使用EntityTemplate實體類和ContentProducer介面支援動態實體。ContentProducer中是通過寫需求的內容到一個輸出資料流,每次請求的時候都會產生。因此,通過EntityTemplate建立實體通常是獨立的,重複性好。

4、通過Response響應請求,例如下面代碼:

<span style="font-size:18px;">if(response.getStatusLine().getStatusCode()==200){byte[] result=EntityUtils.toByteArray(response.getEntity());if(result!=null){String str=new String(result,"UTF-8");}}</span>
上面這段代碼如果直接調用toString()方法,可能會導致某些中文字元出現亂碼的情況,所以使用toByteArray()方法,如果需要轉換成String對象,可以先調用EntityUtils.toByteArray()方法,將訊息實體轉成byte的數組,再由new String[byte[] bArray]轉換成字串。

以上幾個步驟就實現了連網處理資料互動。


Apache的核心功能是HttpClient,通過下面幾行代碼就能發出一個簡單的Get請求並列印響應結果:

<span style="font-size:18px;">try {//建立一個預設的HttpClientHttpClient httpClient=new DefaultHttpClient();//建立一個Get請求HttpGet request=new HttpGet(uri);//發送Get請求,並響應內容轉換成字串String response=httpClient.execute(request,new BasicResponseHandler());} catch (Exception e) {e.printStackTrace();}</span>

如果同時有多個請求需要處理時,我們可以使用多線程,HttpClient提供了建立安全執行緒對象的API,例如下面代碼:

<span style="font-size:18px;">private static final String CHARSET=HTTP.UTF_8;private static HttpClient httpClient;private HttpTest(){}public static synchronized HttpClient getHttpClient(){if(null==httpClient){HttpParams params=new BasicHttpParams();//設定參數HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);HttpProtocolParams.setContentCharset(params, CHARSET);HttpProtocolParams.setUseExpectContinue(params, true);HttpProtocolParams.setUserAgent(params, "Mozilla/5.0(Linux,U;Android 4.0;en-us;.....)");//從串連池中取串連的逾時時間ConnManagerParams.setTimeout(params, 2000);//連線逾時HttpConnectionParams.setConnectionTimeout(params,2000);//請求逾時HttpConnectionParams.setSoTimeout(params, 2000);//設定HttpClient支援HTTP和HTTPS兩種模式SchemeRegistry sr=new SchemeRegistry();sr.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));sr.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 440));//使用安全執行緒的串連管理來建立HttpClientClientConnectionManager ccm=new ThreadSafeClientConnManager(params, sr);httpClient=new DefaultHttpClient(ccm,params);}return httpClient;}</span>

在上面代碼中,使用ThreadSafeClientConnManager 來建立安全執行緒的HttpClent。





轉載請註明出處:http://blog.csdn.net/hai_qing_xu_kong/article/details/42836319 情緒控_








一起學android之Apache介面(17)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.