[关闭]
@liter 2015-10-23T07:48:47.000000Z 字数 6215 阅读 4600

Android网络通信框架LiteHttp 第九节:POST方式的多种类型数据传输

litehttp2.x版本系列教程


官网: http://litesuits.com

QQ群: 大群 47357508,二群 42960650

本系列文章面向android开发者,展示开源网络通信框架LiteHttp的主要用法,并讲解其关键功能的运作原理,同时传达了一些框架作者在日常开发中的一些最佳实践和经验。

本系列文章目录总览: https://zybuluo.com/liter/note/186513


第九节:LiteHttp之POST方式的多种类型数据传输

POST方式可以传递大量的数据到服务器,包括图片、音乐、文本等各种多媒体文件,这节主要来说明下lite-http的集中数据传输形式,包括:

  • 字符串上传
  • UrlEncodedForm上传
  • 对象自动转JSON上传
  • 对象序列化后上传
  • 字节上传
  • 单文件上传
  • 单输入流上传
  • 多文件(表单)上传

话不多讲,看代码:

  1. // POST Multi-Form Data
  2. final ProgressDialog postProgress = new ProgressDialog(this);
  3. postProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  4. postProgress.setIndeterminate(false);
  5. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  6. builder.setTitle("POST DATA TEST");
  7. String[] array = new String[]{
  8. "字符串上传",
  9. "UrlEncodedForm上传",
  10. "对象自动转JSON上传",
  11. "对象序列化后上传",
  12. "字节上传",
  13. "单文件上传",
  14. "单输入流上传",
  15. "多文件(表单)上传"
  16. };
  17. final StringRequest postRequest = new StringRequest(uploadUrl)
  18. .setMethod(HttpMethods.Post)
  19. .setHttpListener(new HttpListener<String>(true, false, true) {
  20. @Override
  21. public void onStart(AbstractRequest<String> request) {
  22. super.onStart(request);
  23. postProgress.show();
  24. }
  25. @Override
  26. public void onUploading(AbstractRequest<String> request, long total, long len) {
  27. postProgress.setMax((int) total);
  28. postProgress.setProgress((int) len);
  29. }
  30. @Override
  31. public void onEnd(Response<String> response) {
  32. postProgress.dismiss();
  33. if (response.isConnectSuccess()) {
  34. HttpUtil.showTips(activity, "Upload Success", response.getResult() + "");
  35. } else {
  36. HttpUtil.showTips(activity, "Upload Failure", response.getException() + "");
  37. }
  38. response.printInfo();
  39. }
  40. });
  41. builder.setItems(array, new DialogInterface.OnClickListener() {
  42. @Override
  43. public void onClick(DialogInterface dialog, int which) {
  44. switch (which) {
  45. case 0:
  46. postRequest.setHttpBody(new StringBody("hello lite: 你好,Lite!"));
  47. break;
  48. case 1:
  49. LinkedList<NameValuePair> pList = new LinkedList<NameValuePair>();
  50. pList.add(new NameValuePair("key1", "value-haha"));
  51. pList.add(new NameValuePair("key2", "value-hehe"));
  52. postRequest.setHttpBody(new UrlEncodedFormBody(pList));
  53. break;
  54. case 2:
  55. postRequest.setHttpBody(new JsonBody(new UserParam(168, "haha-key")));
  56. break;
  57. case 3:
  58. ArrayList<String> list = new ArrayList<String>();
  59. list.add("a");
  60. list.add("b");
  61. list.add("c");
  62. postRequest.setHttpBody(new SerializableBody(list));
  63. break;
  64. case 4:
  65. postRequest.setHttpBody(new ByteArrayBody(new byte[]{1, 2, 3, 4, 5, 15, 18, 127}));
  66. break;
  67. case 5:
  68. postRequest.setHttpBody(new FileBody(new File("/sdcard/litehttp.txt")));
  69. break;
  70. case 6:
  71. FileInputStream fis = null;
  72. try {
  73. fis = new FileInputStream(new File("/sdcard/aaa.jpg"));
  74. } catch (Exception e) {
  75. e.printStackTrace();
  76. }
  77. postRequest.setHttpBody(new InputStreamBody(fis));
  78. break;
  79. case 7:
  80. fis = null;
  81. try {
  82. fis = new FileInputStream(new File("/sdcard/litehttp.txt"));
  83. } catch (Exception e) {
  84. e.printStackTrace();
  85. }
  86. MultipartBody body = new MultipartBody();
  87. body.addPart(new StringPart("key1", "hello"));
  88. body.addPart(new StringPart("key2", "很高兴见到你", "utf-8", null));
  89. body.addPart(new BytesPart("key3", new byte[]{1, 2, 3}));
  90. body.addPart(new FilePart("pic", new File("/sdcard/aaa.jpg"), "image/jpeg"));
  91. body.addPart(new InputStreamPart("litehttp", fis, "litehttp.txt", "text/plain"));
  92. postRequest.setHttpBody(body);
  93. break;
  94. }
  95. liteHttp.executeAsync(postRequest);
  96. }
  97. });
  98. AlertDialog dialog = builder.create();
  99. dialog.setCanceledOnTouchOutside(true);
  100. dialog.show();

服务器端接受代码大致如下,以Servlet为例,其他语言自行脑补:

  1. /**
  2. * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
  3. */
  4. protected void doPost(HttpServletRequest request,
  5. HttpServletResponse response) throws ServletException, IOException {
  6. //String fileDir = "D:\\Downloads";
  7. //这是我的Mac笔记本上的位置,开发者设置为合适自己的文件夹,尤其windows系统。
  8. String fileDir = "/Users/Matianyu/Downloads";
  9. String contentType = request.getContentType();
  10. // 接受一般参数
  11. Map<String, String[]> map = request.getParameterMap();
  12. if (map.size() > 0) {
  13. for (Entry<String, String[]> en : map.entrySet()) {
  14. System.out.println(en.getKey() + " : " + Arrays.toString(en.getValue()));
  15. }
  16. }
  17. response.setContentType("text/plain");
  18. response.setCharacterEncoding("UTF-8");
  19. // 接受文件和流
  20. PrintWriter writer = response.getWriter();
  21. writer.println("contentType:" + contentType);
  22. if (contentType != null) {
  23. if (contentType.startsWith("multipart")) {
  24. //向客户端发送响应正文
  25. try {
  26. //创建一个基于硬盘的FileItem工厂
  27. DiskFileItemFactory factory = new DiskFileItemFactory();
  28. //设置向硬盘写数据时所用的缓冲区的大小,此处为4K
  29. factory.setSizeThreshold(4 * 1024);
  30. //设置临时目录
  31. factory.setRepository(new File(fileDir));
  32. //创建一个文件上传处理器
  33. ServletFileUpload upload = new ServletFileUpload(factory);
  34. //设置允许上传的文件的最大尺寸,此处为100M
  35. upload.setSizeMax(100 * 1024 * 1024);
  36. Map<String, List<FileItem>> itemMap = upload.parseParameterMap(request);
  37. for (List<FileItem> items : itemMap.values()) {
  38. Iterator iter = items.iterator();
  39. while (iter.hasNext()) {
  40. FileItem item = (FileItem) iter.next();
  41. if (item.isFormField()) {
  42. processFormField(item, writer); //处理普通的表单域
  43. } else {
  44. processUploadedFile(fileDir, item, writer); //处理上传文件
  45. }
  46. }
  47. }
  48. } catch (Exception ex) {
  49. ex.printStackTrace();
  50. }
  51. } else if (contentType.contains("text")
  52. || contentType.contains("json")
  53. || contentType.contains("application/x-www-form-urlencoded")
  54. || contentType.contains("xml")) {
  55. processString(request);
  56. } else {
  57. processEntity(fileDir, request);
  58. }
  59. } else {
  60. processString(request);
  61. }
  62. writer.print("upload over. ");
  63. }
  64. private void processString(HttpServletRequest request) {
  65. try {
  66. BufferedReader reader = request.getReader();
  67. StringBuilder sb = new StringBuilder();
  68. String line;
  69. while ((line = reader.readLine()) != null) {
  70. sb.append(line);
  71. sb.append("\n\r");
  72. }
  73. } catch (IOException e) {
  74. e.printStackTrace();
  75. }
  76. }
  77. private void processEntity(String dir, HttpServletRequest request) {
  78. try {
  79. File uploadFile = new File(dir + "a-upload");
  80. InputStream input = request.getInputStream();
  81. OutputStream output = new FileOutputStream(uploadFile);
  82. byte[] buffer = new byte[4096];
  83. int n = -1;
  84. while ((n = input.read(buffer)) != -1) {
  85. if (n > 0) {
  86. output.write(buffer, 0, n);
  87. }
  88. }
  89. output.close();
  90. } catch (IOException e) {
  91. e.printStackTrace();
  92. }
  93. }
  94. /**
  95. * 处理表单字符数据
  96. */
  97. private void processFormField(FileItem item, PrintWriter writer) {
  98. String name = item.getFieldName();
  99. String value = item.getString();
  100. writer.println("Form Part [" + name + "] value :" + value + "\r\n");
  101. }
  102. /**
  103. * 处理表单文件
  104. */
  105. private void processUploadedFile(String filePath, FileItem item, PrintWriter writer) throws Exception {
  106. String filename = item.getName();
  107. int index = filename.lastIndexOf("\\");
  108. filename = filename.substring(index + 1, filename.length());
  109. long fileSize = item.getSize();
  110. if (filename.equals("") && fileSize == 0)
  111. return;
  112. File uploadFile = new File(filePath + "/" + filename);
  113. item.write(uploadFile);
  114. writer.println(
  115. "File Part [" + filename + "] is saved." + " contentType: " + item
  116. .getContentType() + " , size: " + fileSize + "\r\n");
  117. }

当然,需要引入 apache的开源项目commons-fileupload等jar包。
此节比较枯燥,满眼是代码。
shut up, just show me the code.

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注