Android實戰之HttpClient

來源:互聯網
上載者:User

最近在看Android的開發,其中用到了HttpClient來提交或者擷取server端的資料,但是Android內建的API還是有點不好用,所以自己根據自己的需要就做了一個封裝,如下:

 

HttpConnectionUtil類是一個工具類,其中提供了同步和非同步方法呼叫,並且目前是支援http的Get和Post方法

import java.io.BufferedReader;<br />import java.io.IOException;<br />import java.io.InputStreamReader;<br />import java.io.UnsupportedEncodingException;<br />import java.net.URLEncoder;<br />import java.util.ArrayList;<br />import java.util.List;<br />import java.util.Map;<br />import org.apache.http.HttpResponse;<br />import org.apache.http.HttpStatus;<br />import org.apache.http.NameValuePair;<br />import org.apache.http.client.ClientProtocolException;<br />import org.apache.http.client.HttpClient;<br />import org.apache.http.client.entity.UrlEncodedFormEntity;<br />import org.apache.http.client.methods.HttpGet;<br />import org.apache.http.client.methods.HttpPost;<br />import org.apache.http.client.methods.HttpUriRequest;<br />import org.apache.http.impl.client.DefaultHttpClient;<br />import org.apache.http.message.BasicNameValuePair;<br />import android.os.Handler;<br />import android.util.Log;<br />public class HttpConnectionUtil {<br />public static enum HttpMethod {GET, POST}</p><p>public void asyncConnect(final String url, final HttpMethod method, final HttpConnectionCallback callback) {<br />asyncConnect(url, null, method, callback);<br />}</p><p>public void syncConnect(final String url, final HttpMethod method, final HttpConnectionCallback callback) {<br />syncConnect(url, null, method, callback);<br />}</p><p>public void asyncConnect(final String url, final Map<String, String> params,<br />final HttpMethod method, final HttpConnectionCallback callback) {<br />Handler handler = new Handler();<br />Runnable runnable = new Runnable() {<br />public void run() {<br />syncConnect(url, params, method, callback);<br />}<br />};<br />handler.post(runnable);<br />}</p><p>public void syncConnect(final String url, final Map<String, String> params,<br />final HttpMethod method, final HttpConnectionCallback callback) {<br />String json = null;<br />BufferedReader reader = null;</p><p>try {<br />HttpClient client = new DefaultHttpClient();<br />HttpUriRequest request = getRequest(url, params, method);<br />HttpResponse response = client.execute(request);<br />if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {<br />reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));<br />StringBuilder sb = new StringBuilder();<br />for (String s = reader.readLine(); s != null; s = reader.readLine()) {<br />sb.append(s);<br />}<br />json = sb.toString();<br />}<br />} catch (ClientProtocolException e) {<br />Log.e("HttpConnectionUtil", e.getMessage(), e);<br />} catch (IOException e) {<br />Log.e("HttpConnectionUtil", e.getMessage(), e);<br />} finally {<br />try {<br />if (reader != null) {<br />reader.close();<br />}<br />} catch (IOException e) {<br />// ignore me<br />}<br />}<br />callback.execute(json);<br />}</p><p>private HttpUriRequest getRequest(String url, Map<String, String> params, HttpMethod method) {<br />if (method.equals(HttpMethod.POST)) {<br />List<NameValuePair> listParams = new ArrayList<NameValuePair>();<br />if (params != null) {<br />for (String name : params.keySet()) {<br />listParams.add(new BasicNameValuePair(name, params.get(name)));<br />}<br />}<br />try {<br />UrlEncodedFormEntity entity = new UrlEncodedFormEntity(listParams);<br />HttpPost request = new HttpPost(url);<br />request.setEntity(entity);<br />return request;<br />} catch (UnsupportedEncodingException e) {<br />// Should not come here, ignore me.<br />throw new java.lang.RuntimeException(e.getMessage(), e);<br />}<br />} else {<br />if (url.indexOf("?") < 0) {<br />url += "?";<br />}<br />if (params != null) {<br />for (String name : params.keySet()) {<br />url += "&" + name + "=" + URLEncoder.encode(params.get(name));<br />}<br />}<br />HttpGet request = new HttpGet(url);<br />return request;<br />}<br />}<br />}<br /> 

 

 

HttpConnectionCallback類是一個回調類,用來處理請求完畢後的邏輯。

public interface HttpConnectionCallback {<br />/**<br /> * Call back method will be execute after the http request return.<br /> * @param response the response of http request.<br /> * The value will be null if any error occur.<br /> */<br />void execute(String response);<br />}<br /> 

 

 

相關文章

聯繫我們

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