Android中Http請求類的封裝

來源:互聯網
上載者:User

在Android的網路開發中,會常用到Http請求,為了避免代碼的重複編寫,我們要學會封裝一個Http請求類。

方法1:

public class Network {public String  makeHttpRequest(String url, List<NameValuePair> params) {try{ .............}catch (JSONException e) {         e.printStackTrace();    }    }}

首先在makeHttpResquest 的方法中建立HTTP Post聯機

DefaultHttpClient httpClient = new DefaultHttpClient();

new 一個新的httppost對象

HttpPost httpPost = new HttpPost(url);

佈建要求時候的編碼格式

httpPost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));

執行請求

HttpResponse httpResponse = httpClient.execute(httpPost);HttpEntity httpEntity = httpResponse.getEntity();is = httpEntity.getContent();        

利用BufferedReader擷取輸入資料流

BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));StringBuilder sb = new StringBuilder();String line = null;while ((line = reader.readLine()) != null) {        sb.append(line + "\n");        }is.close();

return line;

當然這中間要捕獲各種異常。最後當我們需要用的時候 執行個體化出一個就行了。

Network net=new Network();net.makeHttpRequest(url_up,params);

方法2:

只對url進行請求,這個執行個體在我用Dom解析XML檔案時候用到了:

public String getXmlFromUrl(String url) {        String xml = null;        try {            // defaultHttpClient            DefaultHttpClient httpClient = new DefaultHttpClient();            HttpPost httpPost = new HttpPost(url);            HttpResponse httpResponse = httpClient.execute(httpPost);            HttpEntity httpEntity = httpResponse.getEntity();            xml = EntityUtils.toString(httpEntity,"utf-8");        } catch (UnsupportedEncodingException e) {            e.printStackTrace();        } catch (ClientProtocolException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }        // return XML        return xml;    }    

跟方法一不同的是,這裡用到了 EntityUtils 這個類,直接獲得httpEntity。

 

相關文章

聯繫我們

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