zoukankan      html  css  js  c++  java
  • Android中Http请求类的封装

    在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。

  • 相关阅读:
    浅谈常量
    运算符
    TTL与CMOS门电路
    16位CRC校验_Delphi
    DXP快捷键记录(红色为经常用到的)
    论EFMS模拟量部分采集电路的修改
    稳压二极管应用电路_转载
    TVS二极管
    TryEnterCriticalSection___Delphi
    很好用的一个翻译插件
  • 原文地址:https://www.cnblogs.com/LIANQQ/p/2828178.html
Copyright © 2011-2022 走看看