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。

  • 相关阅读:
    读取web.xml中设置的参数
    在服务端中,读取properties资源文件中的数据
    window下,nodejs安装http-server,并开启HTTP服务器
    跨域请求资源的方式
    IView 给Submenu增加click事件失效解决方案
    Vue -- mounted方法中调用methods的方法(并取出mounted方法中回调函数的值)
    IView 使用Table组件时实现给某一列添加click事件
    物联网协议CoAP协议学习
    电脑操作
    物联网协议
  • 原文地址:https://www.cnblogs.com/LIANQQ/p/2828178.html
Copyright © 2011-2022 走看看