Android中Http请求类的封装

来源:互联网 发布:网络上gm是什么意思啊 编辑:程序博客网 时间:2024/05/07 06:06

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。

 


0 0
原创粉丝点击