快速开发之xUtils(四)HttpUtils详细介绍

来源:互联网 发布:亚信数据全球总部 编辑:程序博客网 时间:2024/05/17 01:48

转载:http://www.apkbus.com/forum.php?mod=viewthread&tid=157645&highlight=xUtils

案例下载:http://download.csdn.net/detail/huningjun/8645595或者https://github.com/wyouflf/xUtils

  HttpUtils模块主要是封装了http请求和响应方面的操作。做过这方面的朋友应该非常熟悉。一般都是把请求封装好。然后调用execute方法,得到响应。然后在处理这个响应。
  1. HttpResponse response = client. execute(request, context);
  2.                     responseInfo = handleResponse(response);
复制代码


                               
由于网络响应需要一定的时间。所以往往都放在后台进行处理。根据结果和过程,执行回调方法。
如下:
  1. @Override
  2.     protected Void doInBackground(Object... params) {
  3.         if (this.state == State.STOPPED || params == null || params.length == 0) return null;

  4.         if (params.length > 3) {
  5.             fileSavePath = String.valueOf(params[1]);
  6.             isDownloadingFile = fileSavePath != null;
  7.             autoResume = (Boolean) params[2];
  8.             autoRename = (Boolean) params[3];
  9.         }

  10.         try {
  11.             if (this.state == State.STOPPED) return null;
  12.             // init request & requestUrl
  13.             request = (HttpRequestBase) params[0];
  14.             requestUrl = request.getURI().toString();
  15.             if (callback != null) {
  16.                 callback.setRequestUrl(requestUrl);
  17.             }

  18.             this.publishProgress(UPDATE_START);

  19.             lastUpdateTime = SystemClock.uptimeMillis();

  20.             ResponseInfo<T> responseInfo = sendRequest(request);
  21.             if (responseInfo != null) {
  22.                 this.publishProgress(UPDATE_SUCCESS, responseInfo);
  23.                 return null;
  24.             }
  25.         } catch (HttpException e) {
  26.             this.publishProgress(UPDATE_FAILURE, e, e.getMessage());
  27.         }

  28.         return null;
  29.     }
复制代码

                               
这部分思路已经清楚。则项目sample里的文件上传和下载也就容易理解了。
        1.文件下载
        sample里下载文件调用了一下的方法:
  1. downloadManager.addNewDownload(downloadAddrEdit.getText().toString(),
  2.                     "力卓文件",
  3.                     target,
  4.                     true, // 如果目标文件存在,接着未完成的部分继续下载。服务器不支持RANGE时将从新下载。
  5.                     false, // 如果从请求返回信息中获取到文件名,下载完成后自动重命名。
  6.                     null);
  7.       它会把这个下载任务保存到数据库,主要用来实现断点续传。当用户停止下载任务时,下次可以从数据库中获取到当前下载进度。实现断点续传。
  8.        当服务端,返回respose后,文件下载的处理如下。
  9.            public File handleEntity(HttpEntity entity,
  10.                              RequestCallBackHandler callBackHandler,
  11.                              String target,
  12.                              boolean isResume,
  13.                              String responseFileName) throws IOException {
  14.         if (entity == null || TextUtils.isEmpty(target)) {
  15.             return null;
  16.         }

  17.         File targetFile = new File(target);

  18.         if (!targetFile.exists()) {
  19.             File dir = targetFile.getParentFile();
  20.             if (!dir.exists()) {
  21.                 dir.mkdirs();
  22.             }
  23.             targetFile.createNewFile();
  24.         }

  25.         long current = 0;
  26.         InputStream inputStream = null;
  27.         FileOutputStream fileOutputStream = null;

  28.         try {

  29.             if (isResume) {
  30.                 current = targetFile.length();
  31.                 fileOutputStream = new FileOutputStream(target, true);
  32.             } else {
  33.                 fileOutputStream = new FileOutputStream(target);
  34.             }

  35.             long total = entity.getContentLength() + current;

  36.             if (callBackHandler != null && !callBackHandler.updateProgress(total, current, true)) {
  37.                 return targetFile;
  38.             }


  39.             inputStream = entity.getContent();
  40.             BufferedInputStream bis = new BufferedInputStream(inputStream);

  41.             byte[] tmp = new byte[4096];
  42.             int len;
  43.             while ((len = bis.read(tmp)) != -1) {
  44.                 fileOutputStream.write(tmp, 0, len);
  45.                 current += len;
  46.                 if (callBackHandler != null) {
  47.                     if (!callBackHandler.updateProgress(total, current, false)) {
  48.                         return targetFile;
  49.                     }
  50.                 }
  51.             }
  52.             fileOutputStream.flush();
  53.             if (callBackHandler != null) {
  54.                 callBackHandler.updateProgress(total, current, true);
  55.             }
  56.         } finally {
  57.             IOUtils.closeQuietly(inputStream);
  58.             IOUtils.closeQuietly(fileOutputStream);
  59.         }

  60.         if (targetFile.exists() && !TextUtils.isEmpty(responseFileName)) {
  61.             File newFile = new File(targetFile.getParent(), responseFileName);
  62.             while (newFile.exists()) {
  63.                 newFile = new File(targetFile.getParent(), System.currentTimeMillis() + responseFileName);
  64.             }
  65.             return targetFile.renameTo(newFile) ? newFile : targetFile;
  66.         } else {
  67.             return targetFile;
  68.         }
  69.     }
复制代码

                               
2.文件上传。
        我对sample进行了稍微的修改,增加了文件上传的测试例子。(原例子只是注释掉了,只需要增加一个入口即可)
        客户端代码已经有了。只需要增加个服务端进行接收。服务端我简单处理了一下。就是一个servlet,在dopost方法中进行处理。代码如下:
  1. public void doPost(HttpServletRequest request, HttpServletResponse response)
  2.                         throws ServletException, IOException {

  3.                  String fileName = request.getParameter("fileName");
  4.                 
  5.                 InputStream inputStream = null;
  6.                 FileOutputStream fileOutputStream = null;

  7.                 try {
  8.                          String target = "/home/song/test/"+fileName;
  9.                              File targetFile = new File(target);

  10.                           if (!targetFile.exists()) {
  11.                               File dir = targetFile.getParentFile();
  12.                               if (!dir.exists()) {
  13.                                   dir.mkdirs();
  14.                               }
  15.                               targetFile.createNewFile();
  16.                           }

  17.                          fileOutputStream = new FileOutputStream(target);
  18.                   
  19.                     inputStream = request.getInputStream();
  20.                     BufferedInputStream bis = new BufferedInputStream(inputStream);

  21.                     byte[] tmp = new byte[4096];
  22.                     int len;
  23.                     while ((len = bis.read(tmp)) != -1) {
  24.                         fileOutputStream.write(tmp, 0, len);                  
  25.                      
  26.                     }
  27.                     fileOutputStream.flush();
  28.                     response(response,true);
  29.                 }catch (Exception e) {
  30.                            response(response,false);
  31.                         } finally {
  32.                         try {
  33.                                         if(inputStream!=null)
  34.                                         {
  35.                                                 inputStream.close();
  36.                                         }
  37.                                 } catch (Exception e) {
  38.                                         // TODO: handle exception
  39.                                 }
  40.                         try {
  41.                                         if(fileOutputStream!=null)
  42.                                         {
  43.                                                 fileOutputStream.close();
  44.                                         }
  45.                                 } catch (Exception e) {
  46.                                         // TODO: handle exception
  47.                                 }
  48.                
  49.                 }
  50.                 
  51.         }
复制代码


0 0
原创粉丝点击