天天看点

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

转载: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.                 InputStream inputStream = null;
  5.                 FileOutputStream fileOutputStream = null;
  6.                 try {
  7.                          String target = "/home/song/test/"+fileName;
  8.                              File targetFile = new File(target);
  9.                           if (!targetFile.exists()) {
  10.                               File dir = targetFile.getParentFile();
  11.                               if (!dir.exists()) {
  12.                                   dir.mkdirs();
  13.                               }
  14.                               targetFile.createNewFile();
  15.                           }
  16.                          fileOutputStream = new FileOutputStream(target);
  17.                     inputStream = request.getInputStream();
  18.                     BufferedInputStream bis = new BufferedInputStream(inputStream);
  19.                     byte[] tmp = new byte[4096];
  20.                     int len;
  21.                     while ((len = bis.read(tmp)) != -1) {
  22.                         fileOutputStream.write(tmp, 0, len);                  
  23.                     }
  24.                     fileOutputStream.flush();
  25.                     response(response,true);
  26.                 }catch (Exception e) {
  27.                            response(response,false);
  28.                         } finally {
  29.                         try {
  30.                                         if(inputStream!=null)
  31.                                         {
  32.                                                 inputStream.close();
  33.                                         }
  34.                                 } catch (Exception e) {
  35.                                         // TODO: handle exception
  36.                                 }
  37.                         try {
  38.                                         if(fileOutputStream!=null)
  39.                                         {
  40.                                                 fileOutputStream.close();
  41.                                         }
  42.                                 } catch (Exception e) {
  43.                                         // TODO: handle exception
  44.                                 }
  45.                 }
  46.         }

复制代码