最近在看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 />