Android中用戶端請求伺服器端的方式講解(一)附源碼

來源:互聯網
上載者:User

標籤:

Android中用戶端請求伺服器端的兩種方式:Post方式和Get方式
在這裡不直接贅述了,直接上源碼如下:
(1).Post的方式:

/**     * Post的請求方式     *      * @param model     *            請求序號     * @param paramList     *            用戶端請求的資料參數列表     * @return     */    public JSONObject doPost(int model, List<NameValuePair> paramList) {        try {            // 用戶端向伺服器發送請求的資料            List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();            params.add(new BasicNameValuePair("param1", "中國"));            params.add(new BasicNameValuePair("param2", "美國"));            // 1.定義請求的方式對象:            HttpPost post = new HttpPost(Base_URL);            // 2.定義請求的用戶端對象            HttpClient client = new DefaultHttpClient();            // 將請求的資料封裝在實體類中            HttpEntity entity = new UrlEncodedFormEntity(paramList, HTTP.UTF_8);            // 將實體類放置在URL中            post.setEntity(entity);            // 3.執行請求,返迴響應的對象            HttpResponse response = client.execute(post);            if (response != null                    && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {                // 獲得從伺服器中返回的結果:從伺服器中返回的結果是字串的形式                String result = EntityUtils.toString(response.getEntity(),                        HTTP.UTF_8);                if (result.startsWith("{")) {                    try {                        return new JSONObject(result);                    } catch (JSONException e) {                        e.printStackTrace();                    }                }            }        } catch (ClientProtocolException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }        return null;    }

(2).Get方式:

 /**     *      * @param model     *            請求序號     * @param paramList     *            用戶端請求的資料參數列表     * @return     */    public JSONObject doGet(int model, List<NameValuePair> paramList) {        // 用戶端向伺服器發送請求的資料        // List<BasicNameValuePair> params = new        // ArrayList<BasicNameValuePair>();        // params.add(new BasicNameValuePair("param1", "中國"));        // params.add(new BasicNameValuePair("param2", "美國"));        // 對參數編碼        String param = URLEncodedUtils.format(paramList, HTTP.UTF_8);        // 將URL與參數拼接        // HttpGet get = new HttpGet(Base_URL + "?" + param);        HttpGet get = new HttpGet(Base_URL + "?" + param);        HttpClient httpClient = new DefaultHttpClient();        try {            // 發起GET請求            HttpResponse response = httpClient.execute(get);            if (response != null                    && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {                // 從伺服器中獲得響應的資料                String result = EntityUtils.toString(response.getEntity(),                        HTTP.UTF_8);                try {                    return new JSONObject(result);                } catch (JSONException e) {                    e.printStackTrace();                }            }        } catch (ClientProtocolException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }        return null;    }

整個工具類代碼如下:

package com.chengdong.su.downloaddemo.service;import java.io.IOException;import java.util.ArrayList;import java.util.List;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.NameValuePair;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.client.utils.URLEncodedUtils;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import org.apache.http.protocol.HTTP;import org.apache.http.util.EntityUtils;import org.json.JSONException;import org.json.JSONObject;/** * 用戶端向伺服器端請求的工具 *  * @author scd *  */public class HttpUtil {    /** 請求的URL */    private String Base_URL = "http://www.baidu.com";    /** TAG */    private String TAG = getClass().getSimpleName();    /**     * Post的請求方式     *      * @param model     *            請求序號     * @param paramList     *            用戶端請求的資料參數列表     * @return     */    public JSONObject doPost(int model, List<NameValuePair> paramList) {        try {            // 用戶端向伺服器發送請求的資料            List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();            params.add(new BasicNameValuePair("param1", "中國"));            params.add(new BasicNameValuePair("param2", "美國"));            // 1.定義請求的方式對象:            HttpPost post = new HttpPost(Base_URL);            // 2.定義請求的用戶端對象            HttpClient client = new DefaultHttpClient();            // 將請求的資料封裝在實體類中            HttpEntity entity = new UrlEncodedFormEntity(paramList, HTTP.UTF_8);            // 將實體類放置在URL中            post.setEntity(entity);            // 3.執行請求,返迴響應的對象            HttpResponse response = client.execute(post);            if (response != null                    && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {                // 獲得從伺服器中返回的結果:從伺服器中返回的結果是字串的形式                String result = EntityUtils.toString(response.getEntity(),                        HTTP.UTF_8);                if (result.startsWith("{")) {                    try {                        return new JSONObject(result);                    } catch (JSONException e) {                        e.printStackTrace();                    }                }            }        } catch (ClientProtocolException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }        return null;    }    /**     *      * @param model     *            請求序號     * @param paramList     *            用戶端請求的資料參數列表     * @return     */    public JSONObject doGet(int model, List<NameValuePair> paramList) {        // 用戶端向伺服器發送請求的資料        // List<BasicNameValuePair> params = new        // ArrayList<BasicNameValuePair>();        // params.add(new BasicNameValuePair("param1", "中國"));        // params.add(new BasicNameValuePair("param2", "美國"));        // 對參數編碼        String param = URLEncodedUtils.format(paramList, HTTP.UTF_8);        // 將URL與參數拼接        // HttpGet get = new HttpGet(Base_URL + "?" + param);        HttpGet get = new HttpGet(Base_URL + "?" + param);        HttpClient httpClient = new DefaultHttpClient();        try {            // 發起GET請求            HttpResponse response = httpClient.execute(get);            if (response != null                    && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {                // 從伺服器中獲得響應的資料                String result = EntityUtils.toString(response.getEntity(),                        HTTP.UTF_8);                try {                    return new JSONObject(result);                } catch (JSONException e) {                    e.printStackTrace();                }            }        } catch (ClientProtocolException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }        return null;    }}

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

Android中用戶端請求伺服器端的方式講解(一)附源碼

聯繫我們

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