转载: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
- }
-
- }
-
- }