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