Http的请求方式

Android从网络下载资源有各种方式,可以用HttpClient,也可以用HttpUrlConnection。在这里,总结一下下载的各种方式,也方便今后的使用。


Android访问网络,使用HttpClient还是HttpUrlConnection?我们可以看博文http://blog.csdn.net/guolin_blog/article/details/12452307,该博文有详细介绍。


博文最后总结到:在Android 2.2版本之前,HttpClient拥有较少的bug,因此使用它是最好的选择。而在Android 2.3版本及以后,HttpURLConnection则是最佳的选择。它的API简单,体积较小,因而非常适用于Android项目。压缩和缓存机制可以有效地减少网络访问的流量,在提升速度和省电方面也起到了较大的作用。对于新的应用程序应该更加偏向于使用HttpURLConnection。


1、HttpClient的请求方式


(1)Post方式,示例代码片段:参考博文:http://blog.csdn.net/lideguo1979/article/details/6966534http://blog.csdn.net/zlfxy/article/details/8508176

使用Apache API:

①使用Map来存储参数

Map<String, String> map = new HashMap<String, String>();
map.put(“name”, “wusheng”);
map.put(“password”, “pwd”);

②使用DefaultHttpClient创建HttpClient实例

DefaultHttpClient httpClient = new DefaultHttpClient();

③构建HttpPost

HttpPost post = new HttpPost(“http://wu-sheng.iteye.com”);

④将由Map存储的参数转化为键值参数

List<BasicNameValuePair> postData = new ArrayList<BasicNameValuePair>();
for (Map.Entry<String, String> entry : map.entrySet()) {
postData.add(new BasicNameValuePair(entry.getKey(),
entry.getValue()));
}

⑤使用编码构建Post实体

UrlEncodedFormEntity entity = new UrlEncodedFormEntity(
postData, HTTP.UTF_8);

⑥设置Post实体

post.setEntity(entity);

⑦执行Post方法

HttpResponse response = httpClient.execute(post);

⑧获取返回实体

HttpEntity httpEntity = response.getEntity();

⑨将H中返回实体转化为输入流

InputStream is = httpEntity.getContent();

读取输入流,即返回文本内容

StringBuffer sb = new StringBuffer();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = “”;
while((line=br.readLine())!=null){
sb.append(line);
}


[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <span style="font-family:SimSun;font-size:14px;">private boolean loginServer(String username, String password)    
  2.     {    
  3.         boolean loginValidate = false;    
  4.         //使用apache HTTP客户端实现    
  5.         String urlStr = "http://10.0.2.2:8080/Login/Login";    
  6.         HttpPost request = new HttpPost(urlStr);    
  7.         //如果传递参数多的话,可以对传递的参数进行封装    
  8.         List<NameValuePair> params = new ArrayList<NameValuePair>();    
  9.         //添加用户名和密码    
  10.         params.add(new BasicNameValuePair("username",username));    
  11.         params.add(new BasicNameValuePair("password",password));    
  12.         try    
  13.         {    
  14.             //设置请求参数项    
  15.             request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));    
  16.             HttpClient client = getHttpClient();    
  17.             //执行请求返回相应    
  18.             HttpResponse response = client.execute(request);    
  19.                 
  20.             //判断是否请求成功    
  21.             if(response.getStatusLine().getStatusCode()==200)    
  22.             {    
  23.                 loginValidate = true;    
  24.                 //获得响应信息    
  25.                 responseMsg = EntityUtils.toString(response.getEntity());    
  26.             }    
  27.         }catch(Exception e)    
  28.         {    
  29.             e.printStackTrace();    
  30.         }    
  31.         return loginValidate;    
  32.     }  </span>  
(2) Get方式,示例代码,参考博文:http://blog.csdn.net/lideguo1979/article/details/6966534
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <span style="font-family:SimSun;font-size:14px;">//Http工具类     
  2. import org.apache.http.HttpResponse;     
  3. import org.apache.http.HttpStatus;     
  4. import org.apache.http.client.HttpClient;     
  5. import org.apache.http.client.methods.HttpGet;     
  6. import org.apache.http.impl.client.DefaultHttpClient;     
  7. import org.apache.http.params.BasicHttpParams;     
  8. import org.apache.http.params.HttpConnectionParams;     
  9. import org.apache.http.params.HttpParams;     
  10. import org.apache.http.util.EntityUtils;     
  11.      
  12. public class HttpUtil {     
  13.     public static String getHttpJSON(String url) {     
  14.         HttpGet httpRequest = new HttpGet(url);     
  15.         try {     
  16.             HttpClient httpclient = new DefaultHttpClient();     
  17.             HttpResponse httpResponse = httpclient.execute(httpRequest);     
  18.      
  19.             if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {     
  20.                 String jsonStr = EntityUtils.toString(httpResponse.getEntity(),     
  21.                         "UTF-8");     
  22.                 return jsonStr;     
  23.             }     
  24.         } catch (Exception e) {     
  25.             e.printStackTrace();     
  26.             System.out.println("==============e.printStackTrace() : "     
  27.                     + e.getMessage());     
  28.         }     
  29.         return null;     
  30.     }     
  31.      
  32.     public static int getHttpStatus() {     
  33.         int status = 0;     
  34.         HttpGet httpRequest = new HttpGet(     
  35.                 "http://192.168.0.214/vote/AndroidConnServlet");     
  36.         try {     
  37.             HttpParams httpParameters = new BasicHttpParams();     
  38.             HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);     
  39.             HttpConnectionParams.setSoTimeout(httpParameters, 5000);     
  40.             HttpConnectionParams.setTcpNoDelay(httpParameters, true);     
  41.                  
  42.             HttpClient httpclient = new DefaultHttpClient(httpParameters);     
  43.             HttpResponse httpResponse = httpclient.execute(httpRequest);     
  44.      
  45.             status = httpResponse.getStatusLine().getStatusCode();     
  46.         } catch (Exception e) {     
  47.             e.printStackTrace();     
  48.             System.out     
  49.                     .println("==============connection wifi fail,e.printStackTrace() : "     
  50.                             + e.getMessage());     
  51.         }     
  52.         return status;     
  53.     }     
  54.      
  55. }   </span>  

(3)Get方式和Post方式,该博文介绍的也挺不错的:http://hi.baidu.com/kejisoft/item/9f63615201414617da1635a8

Get方式:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <span style="font-family:SimSun;font-size:14px;">HttpClient mClient = new DefaultHttpClient();   
  2. String targetUrl = "http://hi.baidu.com/kejisoft/pub/show/createtext";   
  3. // 要请求的http地址  
  4. HttpGet mHttpGet = new HttpGet(targetUrl);  
  5. try {  
  6.     HttpResponse mResponse = mClient.execute(mHttpGet); // 执行get请求  
  7.     if(mResponse.getStasusLine().getStatusCode() == HttpStatus.SC_OK) {  
  8.         Log.d("请求OK!");  
  9.         Log.d(EntityUtils.toString(mResponse.getEntity()));  
  10.     }  
  11. catch(Exception e) {  
  12.     Log.d("异常了你要怎么去处理好?" + e);  
  13. }  
  14.     </span>  

 

Post方式:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <span style="font-family:SimSun;font-size:14px;">HttpClient mClient = new DefaultHttpClient();   
  2. String targetUrl = "http://hi.baidu.com/kejisoft/pub/show/createtext";   
  3. // 要请求的http地址  
  4. HttpGet mHttpGet = new HttpGet(targetUrl);  
  5. try {      
  6.     HttpResponse mResponse = mClient.execute(mHttpGet); // 执行get请求      
  7.     if(mResponse.getStasusLine().getStatusCode() == HttpStatus.SC_OK) {          
  8.         Log.d("请求OK!");          
  9.         Log.d(EntityUtils.toString(mResponse.getEntity()));      
  10.     }  
  11. catch(Exception e) {      
  12.     Log.d("异常了你要怎么去处理好?" + e);  
  13. }</span>  

2、HttpUrlConnection的请求方式

示例代码:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <span style="font-family:SimSun;font-size:14px;">String validateURL="http://10.0.2.2:8080/testhttp1/TestServlet?name=yang&pwd=123123";  
  2. try {  
  3.        URL url = new URL(validateUrl); //创建URL对象  
  4.        //返回一个URLConnection对象,它表示到URL所引用的远程对象的连接  
  5.        HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  6.        conn.setConnectTimeout(5000); //设置连接超时为5秒  
  7.        conn.setRequestMethod("GET"); //设定请求方式  
  8.        conn.connect(); //建立到远程对象的实际连接  
  9.        //返回打开连接读取的输入流  
  10.        DataInputStream dis = new DataInputStream(conn.getInputStream());    
  11.       //判断是否正常响应数据   
  12.         if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {  
  13.            System.out.println("网络错误异常!!!!");  
  14.            return  false;  
  15.        }  
  16. catch (Exception e) {  
  17.    e.printStackTrace();  
  18.    System.out.println("这是异常!");  
  19.   } finally {  
  20.     if (conn != null) {  
  21.      conn.disconnect(); //中断连接  
  22.     }  
  23.  }</span>  

3、从网络上下载

(1)网络下载,字节流转换为字符串

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <span style="font-family:SimSun;font-size:14px;">InputStream inputStream = url.openStream();   // 从URL上取得字节流  
  2. ByteArrayOutputStream baos = new ByteArrayOutputStream();  
  3. int ch = -1;  
  4. byte[] buffer = new byte[1024 * 4];  
  5. while ((ch = inputStream.read(buffer)) != -1) {  
  6. baos.write(buffer, 0, ch);  
  7. }  
  8. baos.flush();  
  9. String responseXml = baos.toString(HTTP.UTF_8);  // 依据需求可以选择要要的字符编码格式  
  10. if (isr != null) {   // 打印最后结果  
  11. Log.i(TAG, "得到的字符串是:" + responseXml);  
  12. }</span>  
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <span style="font-family:SimSun;font-size:14px;">final int BUF_SIZE = 1024 * 8;  
  2. byte[] buffer = new byte[BUF_SIZE];  
  3. int bytes = is.read(buffer);  
  4. if (bytes > 0) {  
  5.     int retVal = notify.urlDown(buffer, bytes);  
  6. }  
  7.   
  8. FileOutputStream os = null;  
  9. os = new FileOutputStream(downPath);  
  10. final FileOutputStream oss = os;  
  11. UrlNotify notify = new UrlNotify() {  
  12. @Override  
  13. public int urlDown(byte[] buffer, int bytes) {  
  14. try {  
  15.     oss.write(buffer, 0, bytes);  
  16. catch (IOException e) {  
  17.     return ERROR_FILE_IO;  
  18. }</span>  
 

 

(2)字节流转换为字符流,写入文件代码Uitls示例:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <span style="font-family:SimSun;font-size:14px;">package com.ijinshan.utils;  
  2.   
  3.   
  4.   
  5. import java.io.BufferedWriter;  
  6. import java.io.File;  
  7. import java.io.FileNotFoundException;  
  8. import java.io.FileOutputStream;  
  9. import java.io.IOException;  
  10. import java.io.OutputStreamWriter;  
  11.   
  12. /** 
  13.  * SD卡文件的写入,读取 文本工具类 
  14.  *  
  15.  * @author Gunpoder 
  16.  */  
  17. public final class FileUtil {  
  18.     // 编码字符  
  19.     private static final String CONTENT_CHARSET = "UTF-8";  
  20.     /** 
  21.      * 写入或读取成功 
  22.      */  
  23.     public static final int FILE_WR_SUC = 0;  
  24.     /** 
  25.      * 文件未找到 
  26.      */  
  27.     public static final int FILE_WR_NOTFOUND = 1;  
  28.     /** 
  29.      * IO异常 
  30.      */  
  31.     public static final int FILE_WR_IOEXC = 2;  
  32.   
  33.     /** 
  34.      * 往 SD卡中的指定文件中 一次写入数据 
  35.      *  
  36.      * @param desFilePath 文件全路径 
  37.      * @param content 写入内容 
  38.      * @param append 是否追加 
  39.      * @return FILE_WR_SUC 成功; FILE_WR_NOTFOUND 文件未找到; FILE_WR_IOEXC IO异常; 
  40.      *         FILE_WR_NOTMOUNT Sd卡未挂载 
  41.      */  
  42.     public static int writeOnce(String desFilePath, String content,  
  43.             boolean append) {  
  44.         int res = FILE_WR_SUC;  
  45.         // 记录在隐藏文件夹中  
  46.         File desFile = new File(desFilePath);  
  47.         String strDir = desFile.getParent();  
  48.         File dir = new File(strDir);  
  49.         if (!dir.exists()) {  
  50.             dir.mkdirs();  
  51.         }  
  52.         BufferedWriter writer = null;  
  53.         try {  
  54.             writer = new BufferedWriter(new OutputStreamWriter(  
  55.                         new FileOutputStream(desFile, append), CONTENT_CHARSET));  
  56.             writer.write(content);  
  57.         } catch (FileNotFoundException e) {  
  58.             res = FILE_WR_NOTFOUND;  
  59.             e.printStackTrace();  
  60.         } catch (IOException e) {  
  61.             res = FILE_WR_IOEXC;  
  62.             e.printStackTrace();  
  63.         } finally {  
  64.             try {  
  65.                 if (writer != null) {  
  66.                     writer.close();  
  67.                     writer = null;  
  68.                 }  
  69.             } catch (IOException e) {  
  70.                 e.printStackTrace();  
  71.             }  
  72.         }  
  73.         return res;  
  74.     }  
  75. }  
  76. </span>  

(3)从文件读取数据,代码片段:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <span style="font-family:SimSun;font-size:14px;">public String readFile(String fromPath) {  
  2.         String number = null;  
  3.         StringBuffer sb = new StringBuffer();  
  4.         try {  
  5.             BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(  
  6.                     fromPath), "utf-8"));  
  7.             String line = null;  
  8.             while ((line = reader.readLine()) != null) {    
  9.                 try {  
  10.                     sb.append(line);  
  11.                 } catch (Exception e) {  
  12.                     e.printStackTrace();  
  13.                 }  
  14.             }  
  15.             reader.close();  
  16.         } catch (Exception e) {  
  17.             e.printStackTrace();  
  18.         }  
  19.         return sb.toString();  
  20. }</span>  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值