Android 發送HTTP GET POST 請求以及通過 MultipartEntityBuilder 上傳檔案(二

來源:互聯網
上載者:User

Android 發送HTTP GET POST 請求以及通過 MultipartEntityBuilder 上傳檔案第二版

上次粗略的寫了相同功能的代碼,這次整理修複了之前的一些BUG,結構也大量修改過了,現在應用更加方便點

http://blog.csdn.net/zhouzme/article/details/18940279


直接上代碼了:

ZHttpRequset.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;/** * Created by ZHOUZ on 14-2-3. */public class ZHttpRequest{    public final String HTTP_GET = "GET";    public final String HTTP_POST = "POST";    /**     * 當前請求的 URL     */    protected String url = "";    /**     * HTTP 要求的類型     */    protected String requsetType = HTTP_GET;    /**     * 串連請求的逾時時間     */    protected int connectionTimeout = 5000;    /**     * 讀取遠端資料的逾時時間     */    protected int soTimeout = 10000;    /**     * 服務端返回的狀態代碼     */    protected int statusCode = -1;    /**     * 當前連結的字元編碼     */    protected String charset = HTTP.UTF_8;    /**     * HTTP GET 要求管理器     */    protected HttpRequestBase httpRequest= null;    /**     * HTTP 要求的配置參數     */    protected HttpParams httpParameters= null;    /**     * HTTP 要求響應     */    protected HttpResponse httpResponse= null;    /**     * HTTP 用戶端連線管理員     */    protected HttpClient httpClient= null;    /**     * HTTP POST 方式發送多段資料管理器     */    protected MultipartEntityBuilder multipartEntityBuilder= null;    /**     * 綁定 HTTP 要求的事件監聽器     */    protected OnHttpRequestListener onHttpRequestListener = null;    public ZHttpRequest(){}    public ZHttpRequest(OnHttpRequestListener listener) {        this.setOnHttpRequestListener(listener);    }    /**     * 設定當前請求的連結     *     * @param url     * @return     */    public ZHttpRequest setUrl(String url)    {        this.url = url;        return this;    }    /**     * 設定連線逾時時間     *     * @param timeout 單位(毫秒),預設 5000     * @return     */    public ZHttpRequest setConnectionTimeout(int timeout)    {        this.connectionTimeout = timeout;        return this;    }    /**     * 設定 socket 讀取逾時時間     *     * @param timeout 單位(毫秒),預設 10000     * @return     */    public ZHttpRequest setSoTimeout(int timeout)    {        this.soTimeout = timeout;        return this;    }    /**     * 設定擷取內容的編碼格式     *     * @param charset 預設為 UTF-8     * @return     */    public ZHttpRequest setCharset(String charset)    {        this.charset = charset;        return this;    }    /**     * 擷取當前 HTTP 要求的類型     *     * @return     */    public String getRequestType()    {        return this.requsetType;    }    /**     * 判斷當前是否 HTTP GET 請求     *     * @return     */    public boolean isGet()    {        return this.requsetType == HTTP_GET;    }    /**     * 判斷當前是否 HTTP POST 請求     *     * @return     */    public boolean isPost()    {        return this.requsetType == HTTP_POST;    }    /**     * 擷取 HTTP 要求響應資訊     *     * @return     */    public HttpResponse getHttpResponse()    {        return this.httpResponse;    }    /**     * 擷取 HTTP 用戶端連線管理員     *     * @return     */    public HttpClient getHttpClient()    {        return this.httpClient;    }    /**     * 添加一條 HTTP 要求的 header 資訊     *     * @param name     * @param value     * @return     */    public ZHttpRequest addHeader(String name, String value)    {        this.httpRequest.addHeader(name, value);        return this;    }    /**     * 擷取 HTTP GET 控制器     *     * @return     */    public HttpGet getHttpGet()    {        return (HttpGet) this.httpRequest;    }    /**     * 擷取 HTTP POST 控制器     *     * @return     */    public HttpPost getHttpPost()    {        return (HttpPost) this.httpRequest;    }    /**     * 擷取請求的狀態代碼     *     * @return     */    public int getStatusCode()    {        return this.statusCode;    }    /**     * 通過 GET 方式請求資料     *     * @param url     * @return     * @throws IOException     */    public String get(String url) throws Exception    {        this.requsetType = HTTP_GET;        // 設定當前請求的連結        this.setUrl(url);        // 建立 HTTP GET 請求        this.httpRequest = new HttpGet(this.url);        // 執行用戶端請求        this.httpClientExecute();        // 監聽服務端響應事件並返回服務端內容        return this.checkStatus();    }    /**     * 擷取 HTTP POST 多段資料提交管理器     *     * @return     */    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;    }    /**     * 配置完要 POST 提交的資料後, 執行該方法產生資料實體等待發送     */    public void buildPostEntity()    {        // 產生 HTTP POST 實體        HttpEntity httpEntity = this.multipartEntityBuilder.build();        this.getHttpPost().setEntity(httpEntity);    }    /**     * 發送 POST 請求     *     * @param url     * @return     * @throws Exception     */    public String post(String url) throws Exception    {        this.requsetType = HTTP_POST;        // 設定當前請求的連結        this.setUrl(url);        // 建立 HTTP POST 請求        this.httpRequest = new HttpPost(this.url);        // 執行用戶端請求        this.httpClientExecute();        // 監聽服務端響應事件並返回服務端內容        return this.checkStatus();    }    /**     * 執行 HTTP 要求     *     * @throws Exception     */    protected void httpClientExecute() throws Exception    {        // 配置 HTTP 要求參數        this.httpParameters = new BasicHttpParams();        this.httpParameters.setParameter("charset", this.charset);        // 設定 串連請求逾時時間        HttpConnectionParams.setConnectionTimeout(this.httpParameters, this.connectionTimeout);        // 設定 socket 讀取逾時時間        HttpConnectionParams.setSoTimeout(this.httpParameters, this.soTimeout);        // 開啟一個用戶端 HTTP 要求        this.httpClient = new DefaultHttpClient(this.httpParameters);        // 啟動 HTTP POST 請求執行前的事件監聽回調操作(如: 自訂提交的資料欄位或上傳的檔案等)        this.getOnHttpRequestListener().onRequest(this);        // 發送 HTTP 要求並擷取服務端響應狀態        this.httpResponse = this.httpClient.execute(this.httpRequest);        // 擷取請求返回的狀態代碼        this.statusCode = this.httpResponse.getStatusLine().getStatusCode();    }    /**     * 讀取服務端返回的輸入資料流並轉換成字串返回     *     * @throws Exception     */    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();        }    }    /**     * 監聽服務端響應事件並返回服務端內容     *     * @return     * @throws Exception     */    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;    }    /**     * HTTP 要求操作時的事件監聽介面     */    public interface OnHttpRequestListener    {        /**         * 初始化 HTTP GET 或 POST 請求之前的 header 資訊配置 或 其他資料配置等操作         *         * @param request         * @throws Exception         */        public void onRequest(ZHttpRequest request) throws Exception;        /**         * 當 HTTP 要求響應成功時的回調方法         *         * @param statusCode 目前狀態碼         * @param request         * @return 返回請求獲得的字串內容         * @throws Exception         */        public String onSucceed(int statusCode, ZHttpRequest request) throws Exception;        /**         * 當 HTTP 要求響應失敗時的回調方法         *         * @param statusCode 目前狀態碼         * @param request         * @return 返回請求失敗的提示內容         * @throws Exception         */        public String onFailed(int statusCode, ZHttpRequest request) throws Exception;    }    /**     * 綁定 HTTP 要求的監聽事件     *     * @param listener     * @return     */    public ZHttpRequest setOnHttpRequestListener(OnHttpRequestListener listener)    {        this.onHttpRequestListener = listener;        return this;    }    /**     * 擷取已綁定過的 HTTP 要求監聽事件     *     * @return     */    public OnHttpRequestListener getOnHttpRequestListener()    {        return this.onHttpRequestListener;    }}

在 Activity 中的使用方法(這裡我還是唯寫主體部分代碼):

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 {                // 設定發送請求的 header 資訊                request.addHeader("cookie", "abc=123;456=愛就是幸福;");                // 配置要 POST 的資料                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("http://www.baidu.com");                content = "GET資料:isGet: " + (get.isGet() ? "yes" : "no") + " =>" + content;            } else {                content = post.post("http://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 類型,我是直接拍照後進行上傳用的

關於拍照顯示並上傳的代碼部分:http://blog.csdn.net/zhouzme/article/details/18952201


布局頁面

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical"    >    <ScrollView        android:layout_width="fill_parent"        android:layout_height="fill_parent"        >        <LinearLayout            android:layout_width="fill_parent"            android:layout_height="fill_parent"            android:orientation="vertical"            >            <Button                android:id="@+id/doGet"                android:layout_width="fill_parent"                android:layout_height="wrap_content"                android:padding="10dp"                android:layout_marginBottom="10dp"                android:text="GET請求"                android:onClick="doClick"                />            <Button                android:id="@+id/doPost"                android:layout_width="fill_parent"                android:layout_height="wrap_content"                android:padding="10dp"                android:layout_marginBottom="10dp"                android:text="POST請求"                android:onClick="doClick"                />            <Button                android:id="@+id/doPhoto"                android:layout_width="fill_parent"                android:layout_height="wrap_content"                android:padding="10dp"                android:layout_marginBottom="10dp"                android:text="拍照"                android:onClick="doPhoto"                />            <TextView                android:id="@+id/showContent"                android:layout_width="fill_parent"                android:layout_height="wrap_content"                android:layout_marginBottom="10dp"                />            <ImageView                android:id="@+id/showPhoto"                android:layout_width="fill_parent"                android:layout_height="250dp"                android:scaleType="centerCrop"                android:src="@drawable/add"                android:layout_marginBottom="10dp"                />        </LinearLayout>    </ScrollView></LinearLayout>

至於服務端我用的 PHP ,只是簡單的輸出擷取到的資料而已

<?phpecho 'GET:<br>'. "\n";//print_r(array_map('urldecode', $_GET));print_r($_GET);echo '<br>'. "\n". 'POST:<br>'. "\n";//print_r(array_map('urldecode', $_POST));print_r($_POST);echo '<br>'. "\n". 'FILES:<br>'. "\n";print_r($_FILES);echo '<br>'. "\n". 'COOKIES:<br>'. "\n";print_r($_COOKIE);



聯繫我們

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