轉載: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方法,得到響應。然後在處理這個響應。
- HttpResponse response = client. execute(request, context);
- responseInfo = handleResponse(response);
複制代碼
由于網絡響應需要一定的時間。是以往往都放在背景進行處理。根據結果和過程,執行回調方法。 如下:
- @Override
- protected Void doInBackground(Object... params) {
- if (this.state == State.STOPPED || params == null || params.length == 0) return null;
- if (params.length > 3) {
- fileSavePath = String.valueOf(params[1]);
- isDownloadingFile = fileSavePath != null;
- autoResume = (Boolean) params[2];
- autoRename = (Boolean) params[3];
- }
- try {
- if (this.state == State.STOPPED) return null;
- // init request & requestUrl
- request = (HttpRequestBase) params[0];
- requestUrl = request.getURI().toString();
- if (callback != null) {
- callback.setRequestUrl(requestUrl);
- }
- this.publishProgress(UPDATE_START);
- lastUpdateTime = SystemClock.uptimeMillis();
- ResponseInfo<T> responseInfo = sendRequest(request);
- if (responseInfo != null) {
- this.publishProgress(UPDATE_SUCCESS, responseInfo);
- return null;
- }
- } catch (HttpException e) {
- this.publishProgress(UPDATE_FAILURE, e, e.getMessage());
- }
- return null;
- }
複制代碼
這部分思路已經清楚。則項目sample裡的檔案上傳和下載下傳也就容易了解了。 1.檔案下載下傳 sample裡下載下傳檔案調用了一下的方法:
- downloadManager.addNewDownload(downloadAddrEdit.getText().toString(),
- "力卓檔案",
- target,
- true, // 如果目标檔案存在,接着未完成的部分繼續下載下傳。伺服器不支援RANGE時将從新下載下傳。
- false, // 如果從請求傳回資訊中擷取到檔案名,下載下傳完成後自動重命名。
- null);
- 它會把這個下載下傳任務儲存到資料庫,主要用來實作斷點續傳。當使用者停止下載下傳任務時,下次可以從資料庫中擷取到目前下載下傳進度。實作斷點續傳。
- 當服務端,傳回respose後,檔案下載下傳的處理如下。
- public File handleEntity(HttpEntity entity,
- RequestCallBackHandler callBackHandler,
- String target,
- boolean isResume,
- String responseFileName) throws IOException {
- if (entity == null || TextUtils.isEmpty(target)) {
- return null;
- }
- File targetFile = new File(target);
- if (!targetFile.exists()) {
- File dir = targetFile.getParentFile();
- if (!dir.exists()) {
- dir.mkdirs();
- }
- targetFile.createNewFile();
- }
- long current = 0;
- InputStream inputStream = null;
- FileOutputStream fileOutputStream = null;
- try {
- if (isResume) {
- current = targetFile.length();
- fileOutputStream = new FileOutputStream(target, true);
- } else {
- fileOutputStream = new FileOutputStream(target);
- }
- long total = entity.getContentLength() + current;
- if (callBackHandler != null && !callBackHandler.updateProgress(total, current, true)) {
- return targetFile;
- }
- inputStream = entity.getContent();
- BufferedInputStream bis = new BufferedInputStream(inputStream);
- byte[] tmp = new byte[4096];
- int len;
- while ((len = bis.read(tmp)) != -1) {
- fileOutputStream.write(tmp, 0, len);
- current += len;
- if (callBackHandler != null) {
- if (!callBackHandler.updateProgress(total, current, false)) {
- return targetFile;
- }
- }
- }
- fileOutputStream.flush();
- if (callBackHandler != null) {
- callBackHandler.updateProgress(total, current, true);
- }
- } finally {
- IOUtils.closeQuietly(inputStream);
- IOUtils.closeQuietly(fileOutputStream);
- }
- if (targetFile.exists() && !TextUtils.isEmpty(responseFileName)) {
- File newFile = new File(targetFile.getParent(), responseFileName);
- while (newFile.exists()) {
- newFile = new File(targetFile.getParent(), System.currentTimeMillis() + responseFileName);
- }
- return targetFile.renameTo(newFile) ? newFile : targetFile;
- } else {
- return targetFile;
- }
- }
複制代碼
2. 檔案上傳。 我對sample 進行了稍微的修改,增加了檔案上傳的測試例子。 ( 原例子隻是注釋掉了,隻需要增加一個入口即可) 用戶端代碼已經有了 。隻需要增加個服務端進行接收。服務端我簡單處理了一下。就是一個servlet ,在dopost 方法中進行處理。代碼如下:
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- String fileName = request.getParameter("fileName");
- InputStream inputStream = null;
- FileOutputStream fileOutputStream = null;
- try {
- String target = "/home/song/test/"+fileName;
- File targetFile = new File(target);
- if (!targetFile.exists()) {
- File dir = targetFile.getParentFile();
- if (!dir.exists()) {
- dir.mkdirs();
- }
- targetFile.createNewFile();
- }
- fileOutputStream = new FileOutputStream(target);
- inputStream = request.getInputStream();
- BufferedInputStream bis = new BufferedInputStream(inputStream);
- byte[] tmp = new byte[4096];
- int len;
- while ((len = bis.read(tmp)) != -1) {
- fileOutputStream.write(tmp, 0, len);
- }
- fileOutputStream.flush();
- response(response,true);
- }catch (Exception e) {
- response(response,false);
- } finally {
- try {
- if(inputStream!=null)
- {
- inputStream.close();
- }
- } catch (Exception e) {
- // TODO: handle exception
- }
- try {
- if(fileOutputStream!=null)
- {
- fileOutputStream.close();
- }
- } catch (Exception e) {
- // TODO: handle exception
- }
- }
- }
複制代碼