android网络框架

来源:互联网 发布:淘宝韩版男装店铺 编辑:程序博客网 时间:2024/06/07 14:07
  • volley是一个简单的异步http库,仅此而已。缺点是不支持同步,这点会限制开发模式;不能post大数据,所以不适合用来上传文件。
  • android-async-http。与volley一样是异步网络库,但volley是封装的httpUrlConnection,它是封装的httpClient,而android平台不推荐用HttpClient了,所以这个库已经不适合android平台了。
  • okhttp是高性能的http库,支持同步、异步,而且实现了spdy、http2、websocket协议,api很简洁易用,和volley一样实现了http协议的缓存。picasso就是利用okhttp的缓存机制实现其文件缓存,实现的很优雅,很正确,反例就是UIL(universal image loader),自己做的文件缓存,而且不遵守http缓存机制。
  • retrofit与picasso一样都是在okhttp基础之上做的封装,项目中可以直接用了。

另外
  • AndroidAsync这个网络库使用了nio的方式实现的。okhttp没有提供nio selector的方式,不过nio更适合大量连接的情况,对于移动平台有点杀鸡用牛刀的味道。
  • picasso、uil都不支持inbitmap,项目中有用到picasso的富图片应用需要注意这点。

上传

  1.  /** 
  2.      *  
  3.      * @param params 
  4.      *            传递的普通参数 
  5.      * @param uploadFile 
  6.      *            需要上传的文件名 
  7.      * @param fileFormName 
  8.      *            需要上传文件表单中的名字 
  9.      * @param newFileName 
  10.      *            上传的文件名称,不填写将为uploadFile的名称 
  11.      * @param urlStr 
  12.      *            上传的服务器的路径 
  13.      * @throws IOException 
  14.      */  
  15.     public void uploadForm(Map<String, String> params, String fileFormName,  
  16.             File uploadFile, String newFileName, String urlStr)  
  17.             throws IOException {  
  18.         if (newFileName == null || newFileName.trim().equals("")) {  
  19.             newFileName = uploadFile.getName();  
  20.         }  
  21.   
  22.         StringBuilder sb = new StringBuilder();  
  23.         /** 
  24.          * 普通的表单数据 
  25.          */  
  26.         for (String key : params.keySet()) {  
  27.             sb.append("--" + BOUNDARY + "\r\n");  
  28.             sb.append("Content-Disposition: form-data; name=\"" + key + "\""  
  29.                     + "\r\n");  
  30.             sb.append("\r\n");  
  31.             sb.append(params.get(key) + "\r\n");  
  32.         }  
  33.         /** 
  34.          * 上传文件的头 
  35.          */  
  36.         sb.append("--" + BOUNDARY + "\r\n");  
  37.         sb.append("Content-Disposition: form-data; name=\"" + fileFormName  
  38.                 + "\"; filename=\"" + newFileName + "\"" + "\r\n");  
  39.         sb.append("Content-Type: image/jpeg" + "\r\n");// 如果服务器端有文件类型的校验,必须明确指定ContentType  
  40.         sb.append("\r\n");  
  41.   
  42.         byte[] headerInfo = sb.toString().getBytes("UTF-8");  
  43.         byte[] endInfo = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("UTF-8");  
  44.         System.out.println(sb.toString());  
  45.         URL url = new URL(urlStr);  
  46.         HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  47.         conn.setRequestMethod("POST");  
  48.         conn.setRequestProperty("Content-Type",  
  49.                 "multipart/form-data; boundary=" + BOUNDARY);  
  50.         conn.setRequestProperty("Content-Length", String  
  51.                 .valueOf(headerInfo.length + uploadFile.length()  
  52.                         + endInfo.length));  
  53.         conn.setDoOutput(true);  
  54.   
  55.         OutputStream out = conn.getOutputStream();  
  56.         InputStream in = new FileInputStream(uploadFile);  
  57.         out.write(headerInfo);  
  58.   
  59.         byte[] buf = new byte[1024];  
  60.         int len;  
  61.         while ((len = in.read(buf)) != -1)  
  62.             out.write(buf, 0, len);  
  63.   
  64.         out.write(endInfo);  
  65.         in.close();  
  66.         out.close();  
  67.         if (conn.getResponseCode() == 200) {  
  68.             System.out.println("上传成功");  
  69.         }  
  70.   
  71.     }  



下载

private class DownThread extends Thread {    @Override    public void run() {        super.run();        String urlStr = "http://xcmserver.b0.upaiyun.com/v1.0/app/" + apatchName;        try {            File file = new File(newFilename);            if (file.exists()) {                urlStr = "http://xcmserver.b0.upaiyun.com/v1.0/app/" + apatchName.replace(".apatch", "new.apatch");            }            Log.i("DownLoadPatchThread", "正在下载中" + urlStr);            // 构造URL            URL url = new URL(urlStr);            // 打开连接            URLConnection con = url.openConnection();            if (con != null) {                // 输入流                InputStream is = con.getInputStream();                File filePath = new File(commonPath);                if (!filePath.exists()) {                    boolean bool = filePath.mkdirs();                    if (bool) Log.e("DownLoadPatchThread", "创建文件夹");                }                //如果目标文件已经存在,则删除。产生覆盖旧文件的效果                if (file.exists()) {                    boolean bool = file.delete();                    if (bool) Log.e("DownLoadPatchThread", "删除文件");                }                // 1K的数据缓冲                byte[] bs = new byte[1024];                // 读取到的数据长度                int len;                // 输出的文件流                if (!StringUtils.isEmpty(newFilename)) {                    OutputStream os = new FileOutputStream(newFilename);                    // 开始读取                    while ((len = is.read(bs)) != -1) {                        os.write(bs, 0, len);                    }                    // 完毕,关闭所有链接                    os.close();                }                is.close();                Log.i("DownLoadPatchThread", "下载完毕");                File file_out = new File(newFilename);                //如果目标文件已经存在,则删除。产生覆盖旧文件的效果                if (file_out.exists()) {                    if (MyApplication.getInstance().getmPatchManager() != null) {                        MyApplication.getInstance().getmPatchManager().removeAllPatch();                        MyApplication.getInstance().getmPatchManager().addPatch(newFilename);                        Log.i("DownLoadPatchThread", newFilename + "加载补丁完毕");                    }                }            }        } catch (Exception e) {            e.printStackTrace();        }    }}

断点续传



  1. public class DownLoadUtil {  
  2.     //构造方法略  
  3.     public void download(){  
  4.         List<FileInfo> lists = threadDAO.get(fileInfo.getUrl());  
  5.         FileInfo info = null;  
  6.         if(lists.size() == 0){  
  7.             //第一次下载,创建子线程下载  
  8.             new MyThread(fileInfo).start();  
  9.         }else{  
  10.             //中间开始的  
  11.             info = lists.get(0);  
  12.             new MyThread(info).start();  
  13.         }  
  14.     }  
  15.   
  16.     class MyThread extends Thread{  
  17.         private FileInfo info = null;  
  18.         public MyThread(FileInfo threadInfo) {  
  19.             this.info = threadInfo;  
  20.         }  
  21.         @Override  
  22.         public void run() {  
  23.             //向数据库添加线程信息  
  24.             if(!threadDAO.isExits(info.getUrl())){  
  25.                 threadDAO.insert(info);  
  26.             }  
  27.             HttpURLConnection urlConnection = null;  
  28.             RandomAccessFile randomFile =null;  
  29.             InputStream inputStream = null;  
  30.             try {  
  31.                 URL url = new URL(info.getUrl());  
  32.                 urlConnection = (HttpURLConnection) url.openConnection();  
  33.                 urlConnection.setConnectTimeout(3000);  
  34.                 urlConnection.setRequestMethod("GET");  
  35.                 //设置下载位置  
  36.                 int start = info.getStart() + info.getNow();  
  37.                 urlConnection.setRequestProperty("Range","bytes=" + start + "-" + info.getLength());  
  38.   
  39.                 //设置文件写入位置  
  40.                 File file = new File(DOWNLOAD_PATH,FILE_NAME);  
  41.                 randomFile = new RandomAccessFile(file, "rwd");  
  42.                 randomFile.seek(start);  
  43.   
  44.                 //向Activity发广播  
  45.                 Intent intent = new Intent(ACTION_UPDATE);  
  46.                 finished += info.getNow();  
  47.   
  48.                 if (urlConnection.getResponseCode() == HttpStatus.SC_PARTIAL_CONTENT) {  
  49.                     //获得文件流  
  50.                     inputStream = urlConnection.getInputStream();  
  51.                     byte[] buffer = new byte[512];  
  52.                     int len = -1;  
  53.                     long time = System.currentTimeMillis();  
  54.                     while ((len = inputStream.read(buffer))!= -1){  
  55.                         //写入文件  
  56.                         randomFile.write(buffer,0,len);  
  57.                         //把进度发送给Activity  
  58.                         finished += len;  
  59.                         //看时间间隔,时间间隔大于500ms再发  
  60.                         if(System.currentTimeMillis() - time >500){  
  61.                             time = System.currentTimeMillis();  
  62.                             intent.putExtra("now",finished *100 /fileInfo.getLength());  
  63.                             context.sendBroadcast(intent);  
  64.                         }  
  65.                         //判断是否是暂停状态  
  66.                         if(isPause){  
  67.                             threadDAO.update(info.getUrl(),finished);  
  68.                             return//结束循环  
  69.                         }  
  70.                     }  
  71.                     //删除线程信息  
  72.                     threadDAO.delete(info.getUrl());  
  73.                 }  
  74.             }catch (Exception e){  
  75.                 e.printStackTrace();  
  76.             }finally {//回收工作略  
  77.             }  
  78.         }  
  79.     }  
  80. }  




原创粉丝点击