編輯:關於 Android 程式設計
這是 Android 發送 HTTP GET / POST 請求並通過 MultipartEntityBuilder 上傳文件的第二版。相比第一版,這一版把請求流程重構得更清晰,並引入了事件監聽器(OnHttpRequestListener)來回調請求前配置、成功、失敗等不同階段的狀態。
ZHttpRequest.java
package com.ai9475.util; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.protocol.HTTP; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; public class ZHttpRequest { public final String HTTP_GET = "GET"; public final String HTTP_POST = "POST"; protected String url = ""; protected String requsetType = HTTP_GET; protected int connectionTimeout = 5000; protected int soTimeout = 10000; protected int statusCode = -1; protected String charset = HTTP.UTF_8; protected HttpRequestBase httpRequest= null; protected HttpParams httpParameters= null; protected HttpResponse httpResponse= null; protected HttpClient httpClient= null; protected MultipartEntityBuilder multipartEntityBuilder= null; protected OnHttpRequestListener onHttpRequestListener = null; public ZHttpRequest(){} public ZHttpRequest(OnHttpRequestListener listener) { this.setOnHttpRequestListener(listener); } public ZHttpRequest setUrl(String url) { this.url = url; return this; } public ZHttpRequest setConnectionTimeout(int timeout) { this.connectionTimeout = timeout; return this; } public ZHttpRequest setSoTimeout(int timeout) { this.soTimeout = timeout; return this; } public ZHttpRequest setCharset(String charset) { this.charset = charset; return this; } public String getRequestType() { return this.requsetType; } public boolean isGet() { return this.requsetType == HTTP_GET; } public boolean isPost() { return this.requsetType == HTTP_POST; } public HttpResponse getHttpResponse() { return this.httpResponse; } public HttpClient getHttpClient() { return this.httpClient; } public ZHttpRequest addHeader(String name, String value) { this.httpRequest.addHeader(name, value); return this; } public HttpGet getHttpGet() { return (HttpGet) this.httpRequest; } public HttpPost getHttpPost() { return (HttpPost) this.httpRequest; } public int getStatusCode() { return this.statusCode; } public String get(String url) throws Exception { this.requsetType = HTTP_GET; this.setUrl(url); this.httpRequest = new HttpGet(this.url); this.httpClientExecute(); return this.checkStatus(); } public MultipartEntityBuilder getMultipartEntityBuilder() { if (this.multipartEntityBuilder == null) { this.multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); multipartEntityBuilder.setCharset(Charset.forName(this.charset)); } return this.multipartEntityBuilder; } public void buildPostEntity() { HttpEntity httpEntity = this.multipartEntityBuilder.build(); this.getHttpPost().setEntity(httpEntity); } public String post(String url) throws Exception { this.requsetType = HTTP_POST; this.setUrl(url); this.httpRequest = new HttpPost(this.url); this.httpClientExecute(); return this.checkStatus(); } protected void httpClientExecute() throws Exception { this.httpParameters = new BasicHttpParams(); this.httpParameters.setParameter(charset, this.charset); HttpConnectionParams.setConnectionTimeout(this.httpParameters, this.connectionTimeout); HttpConnectionParams.setSoTimeout(this.httpParameters, this.soTimeout); this.httpClient = new DefaultHttpClient(this.httpParameters); this.getOnHttpRequestListener().onRequest(this); this.httpResponse = this.httpClient.execute(this.httpRequest); this.statusCode = this.httpResponse.getStatusLine().getStatusCode(); } public String getInputStream() throws Exception { InputStream inStream = this.httpResponse.getEntity().getContent(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int len = -1; while ((len = inStream.read(buf)) != -1) { baos.write(buf, 0, len); } inStream.close(); return new String(baos.toByteArray(), this.charset); } protected void shutdownHttpClient() { if (this.httpClient != null && this.httpClient.getConnectionManager() != null) { this.httpClient.getConnectionManager().shutdown(); } } protected String checkStatus() throws Exception { OnHttpRequestListener listener = this.getOnHttpRequestListener(); String content; if (this.statusCode == HttpStatus.SC_OK) { content = listener.onSucceed(this.statusCode, this); } else { content = listener.onFailed(this.statusCode, this); } this.shutdownHttpClient(); return content; } public interface OnHttpRequestListener { public void onRequest(ZHttpRequest request) throws Exception; public String onSucceed(int statusCode, ZHttpRequest request) throws Exception; public String onFailed(int statusCode, ZHttpRequest request) throws Exception; } public ZHttpRequest setOnHttpRequestListener(OnHttpRequestListener listener) { this.onHttpRequestListener = listener; return this; } public OnHttpRequestListener getOnHttpRequestListener() { return this.onHttpRequestListener; } }
MainActivity.java(調用方式)
public void doClick(View view) { ZHttpRequest get = new ZHttpRequest(); get .setCharset(HTTP.UTF_8) .setConnectionTimeout(5000) .setSoTimeout(5000); get.setOnHttpRequestListener(new ZHttpRequest.OnHttpRequestListener() { @Override public void onRequest(ZHttpRequest request) throws Exception { } @Override public String onSucceed(int statusCode, ZHttpRequest request) throws Exception { return request.getInputStream(); } @Override public String onFailed(int statusCode, ZHttpRequest request) throws Exception { return "GET 請求失敗:statusCode" + statusCode; } }); ZHttpRequest post = new ZHttpRequest(); post .setCharset(HTTP.UTF_8) .setConnectionTimeout(5000) .setSoTimeout(10000); post.setOnHttpRequestListener(new ZHttpRequest.OnHttpRequestListener() { private String CHARSET = HTTP.UTF_8; private ContentType TEXT_PLAIN = ContentType.create("text/plain", Charset.forName(CHARSET)); @Override public void onRequest(ZHttpRequest request) throws Exception { request.addHeader("cookie", "abc=123;456=愛就是幸福;"); MultipartEntityBuilder builder = request.getMultipartEntityBuilder(); builder.addTextBody("p1", "abc"); builder.addTextBody("p2", "中文", TEXT_PLAIN); builder.addTextBody("p3", "abc中文cba", TEXT_PLAIN); if (picPath != null && ! "".equals(picPath)) { builder.addTextBody("pic", picPath); builder.addBinaryBody("file", new File(picPath)); } request.buildPostEntity(); } @Override public String onSucceed(int statusCode, ZHttpRequest request) throws Exception { return request.getInputStream(); } @Override public String onFailed(int statusCode, ZHttpRequest request) throws Exception { return "POST 請求失敗:statusCode" + statusCode; } }); TextView textView = (TextView) findViewById(R.id.showContent); String content = "初始內容"; try { if (view.getId() == R.id.doGet) { content = get.get("https://www.baidu.com"); content = "GET數據:isGet: " + (get.isGet() ? "yes" : "no") + " => " + content; } else { content = post.post("https://192.168.1.6/test.php"); content = "POST數據:isPost " + (post.isPost() ? "yes" : "no") + " => " + content; } } catch (IOException e) { content = "IO異常:" + e.getMessage(); } catch (Exception e) { content = "異常:" + e.getMessage(); } textView.setText(content); }
其中 picPath 為 SD 卡裡的圖片路徑(String 類型),場景是拍照後直接上傳。服務端我用的是 PHP,只是簡單地把收到的 GET、POST、FILES、COOKIE 輸出來核對數據。
echo 'GET:'; print_r($_GET); echo 'POST: '; print_r($_POST); echo 'FILES: '; print_r($_FILES); echo 'COOKIES: '; print_r($_COOKIE);
相比第一版,這一版通過監聽器把「請求前準備數據」與「結果處理」職責分離,讓調用方的代碼更聚焦、可讀性更高,也更方便復用。
Android 的基本世界觀:系統簡介、四大組件與開發入門
前言作為一名折騰了半年多的 Android Developer(之所以不敢說「開發經驗」,是因為我還沒能獨立做出一個完善美觀又有使用價值的應用),我深感要系統地掌握安卓開
Android 元件樣式自訂方法詳解
前言Android 提供了許多現成的元件可以使用,但實際開發中,系統自帶元件的樣式往往與我們 App 的風格不一致。這時候就需要自訂一些樣式。本文將講解如何修改元件的樣式
Android ActionBar 完整指南:下拉導航、操作視窗與選項標籤
ActionBar 從 Android 3.0 開始成為標準配備,可以當作 Activity 的標題、承載關鍵操作(搜尋、分享、新增)、充當選單容器,還能做 Tab 與下
AT Commands 修煉手記(三):把 ATCoP 從裡到外拆一遍
這是「AT Commands:從白癡到大師的修煉歷程」系列的第三篇。前面鋪墊完基礎之後,這次要動真格的,把高通平台裡真正幹活的那個模塊——ATCommandProcess