天天看點

快速開發之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.         }

複制代碼