Android分别使用HTTP协议和TCP协议实现上传文件

简介:

http://blog.csdn.net/furongkang/article/details/6838450

Android上传文件有两种方式,第一种是基于Http协议的HttpURLConnection,第二种是基于TCP协议的Socket。 这两种方式的区别是使用HttpURLConnection上传时内部有缓存机制,如果上传较大文件会导致内存溢出。如果用TCP协议Socket方式上传就会解决这种弊端。

HTTP协议HttpURLConnection

1. 通过URL封装路径打开一个HttpURLConnection

2.设置请求方式以及头字段:Content-Type、Content-Length、Host

3.拼接数据发送

示例:

[java]  view plain copy
  1. private static final String BOUNDARY = "---------------------------7db1c523809b2";//数据分割线  
  2.   
  3. public boolean uploadHttpURLConnection(String username, String password, String path) throws Exception {  
  4.     //找到sdcard上的文件  
  5.     File file = new File(Environment.getExternalStorageDirectory(), path);  
  6.                  //仿Http协议发送数据方式进行拼接  
  7.     StringBuilder sb = new StringBuilder();  
  8.     sb.append("--" + BOUNDARY + "\r\n");  
  9.     sb.append("Content-Disposition: form-data; name=\"username\"" + "\r\n");  
  10.     sb.append("\r\n");  
  11.     sb.append(username + "\r\n");  
  12.   
  13.     sb.append("--" + BOUNDARY + "\r\n");  
  14.     sb.append("Content-Disposition: form-data; name=\"password\"" + "\r\n");  
  15.     sb.append("\r\n");  
  16.     sb.append(password + "\r\n");  
  17.   
  18.     sb.append("--" + BOUNDARY + "\r\n");  
  19.     sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + path + "\"" + "\r\n");  
  20.     sb.append("Content-Type: image/pjpeg" + "\r\n");  
  21.     sb.append("\r\n");  
  22.   
  23.     byte[] before = sb.toString().getBytes("UTF-8");  
  24.     byte[] after = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("UTF-8");  
  25.   
  26.     URL url = new URL("http://192.168.1.16:8080/14_Web/servlet/LoginServlet");  
  27.     HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  28.     conn.setRequestMethod("POST");  
  29.     conn.setRequestProperty("Content-Type""multipart/form-data; boundary=" + BOUNDARY);  
  30.     conn.setRequestProperty("Content-Length", String.valueOf(before.length + file.length() + after.length));  
  31.     conn.setRequestProperty("HOST""192.168.1.16:8080");  
  32.     conn.setDoOutput(true);   
  33.   
  34.     OutputStream out = conn.getOutputStream();  
  35.     InputStream in = new FileInputStream(file);  
  36.       
  37.     out.write(before);  
  38.   
  39.     byte[] buf = new byte[1024];  
  40.     int len;  
  41.     while ((len = in.read(buf)) != -1)  
  42.         out.write(buf, 0, len);  
  43.   
  44.     out.write(after);  
  45.   
  46.     in.close();  
  47.     out.close();  
  48.     return conn.getResponseCode() == 200;  
  49. }  

TCP协议Socket

1.我们可以使用Socket发送TCP请求,将上传数据分段发送

示例:

[java]  view plain copy
  1. public boolean uploadBySocket(String username, String password, String path) throws Exception {  
  2.     // 根据path找到SDCard中的文件  
  3.     File file = new File(Environment.getExternalStorageDirectory(), path);  
  4.     // 组装表单字段和文件之前的数据  
  5.     StringBuilder sb = new StringBuilder();  
  6.   
  7.     sb.append("--" + BOUNDARY + "\r\n");  
  8.     sb.append("Content-Disposition: form-data; name=\"username\"" + "\r\n");  
  9.     sb.append("\r\n");  
  10.     sb.append(username + "\r\n");  
  11.   
  12.     sb.append("--" + BOUNDARY + "\r\n");  
  13.     sb.append("Content-Disposition: form-data; name=\"password\"" + "\r\n");  
  14.     sb.append("\r\n");  
  15.     sb.append(password + "\r\n");  
  16.   
  17.     sb.append("--" + BOUNDARY + "\r\n");  
  18.     sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + path + "\"" + "\r\n");  
  19.     sb.append("Content-Type: image/pjpeg" + "\r\n");  
  20.     sb.append("\r\n");  
  21.   
  22.     // 文件之前的数据  
  23.     byte[] before = sb.toString().getBytes("UTF-8");  
  24.     // 文件之后的数据  
  25.     byte[] after = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("UTF-8");  
  26.   
  27.     URL url = new URL("http://192.168.1.199:8080/14_Web/servlet/LoginServlet");  
  28.   
  29.     // 由于HttpURLConnection中会缓存数据, 上传较大文件时会导致内存溢出, 所以我们使用Socket传输  
  30.     Socket socket = new Socket(url.getHost(), url.getPort());  
  31.     OutputStream out = socket.getOutputStream();  
  32.     PrintStream ps = new PrintStream(out, true"UTF-8");  
  33.   
  34.     // 写出请求头  
  35.     ps.println("POST /14_Web/servlet/LoginServlet HTTP/1.1");  
  36.     ps.println("Content-Type: multipart/form-data; boundary=" + BOUNDARY);  
  37.     ps.println("Content-Length: " + String.valueOf(before.length + file.length() + after.length));  
  38.     ps.println("Host: 192.168.1.199:8080");  
  39.       
  40.     InputStream in = new FileInputStream(file);  
  41.   
  42.     // 写出数据  
  43.     out.write(before);  
  44.   
  45.     byte[] buf = new byte[1024];  
  46.     int len;  
  47.     while ((len = in.read(buf)) != -1)  
  48.         out.write(buf, 0, len);  
  49.   
  50.     out.write(after);  
  51.   
  52.     in.close();  
  53.     out.close();  
  54.   
  55.     return true;  
  56. }  


 

搭建服务器,完成上传功能

[java]  view plain copy
  1. package cn.test.web.servlet;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5. import java.util.List;  
  6.   
  7. import javax.servlet.ServletException;  
  8. import javax.servlet.http.HttpServlet;  
  9. import javax.servlet.http.HttpServletRequest;  
  10. import javax.servlet.http.HttpServletResponse;  
  11.   
  12. import org.apache.commons.fileupload.FileItem;  
  13. import org.apache.commons.fileupload.FileItemFactory;  
  14. import org.apache.commons.fileupload.disk.DiskFileItemFactory;  
  15. import org.apache.commons.fileupload.servlet.ServletFileUpload;  
  16.   
  17. public class LoginServlet extends HttpServlet {  
  18.   
  19.     private static final long serialVersionUID = 1L;  
  20.   
  21.     @Override  
  22.     public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  23.         doPost(request, response);  
  24.     }  
  25.   
  26.     @Override  
  27.     public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  28.         boolean isMultipart = ServletFileUpload.isMultipartContent(request);  
  29.         if (isMultipart)  
  30.             try {  
  31.                 FileItemFactory factory = new DiskFileItemFactory();  
  32.                 ServletFileUpload upload = new ServletFileUpload(factory);  
  33.                 List<FileItem> items = upload.parseRequest(request);  
  34.                 File dir = new File(request.getSession().getServletContext().getRealPath("/WEB-INF/upload"));  
  35.                 //创建目录  
  36.                 dir.mkdir();  
  37.                 for (FileItem item : items)  
  38.                     if (item.isFormField())  
  39.                         System.out.println(item.getFieldName() + ": " + item.getString());  
  40.                     else{  
  41.                         item.write(new File(dir,item.getName().substring(item.getName().lastIndexOf("\\")+1)));  
  42.                     }  
  43.             } catch (Exception e) {  
  44.                 e.printStackTrace();  
  45.             }  
  46.         else {  
  47.             System.out.println(request.getMethod());  
  48.             System.out.println(request.getParameter("username"));  
  49.             System.out.println(request.getParameter("password"));  
  50.         }  
  51.     }  
  52. }  

相关文章
|
3月前
|
安全 搜索推荐 Android开发
Android安全性: 解释HTTPS在移动应用中的重要性。
Android安全性: 解释HTTPS在移动应用中的重要性。
21 0
|
3月前
|
缓存 网络协议 安全
计算机网络 TCP、RPC、GRPC、HTTP 对比
【1月更文挑战第1天】计算机网络 TCP、RPC、GRPC、HTTP 对比
|
4天前
|
网络协议 Linux Windows
TCP/IP、Http、Socket之间的区别
TCP/IP、Http、Socket之间的区别
|
6天前
|
网络协议 Java API
深度剖析:Java网络编程中的TCP/IP与HTTP协议实践
【4月更文挑战第17天】Java网络编程重在TCP/IP和HTTP协议的应用。TCP提供可靠数据传输,通过Socket和ServerSocket实现;HTTP用于Web服务,常借助HttpURLConnection或Apache HttpClient。两者结合,构成网络服务基础。Java有多种高级API和框架(如Netty、Spring Boot)简化开发,助力高效、高并发的网络通信。
|
7天前
|
网络协议 安全 API
Android网络和数据交互: 什么是HTTP和HTTPS?在Android中如何进行网络请求?
HTTP和HTTPS是网络数据传输协议,HTTP基于TCP/IP,简单快速,HTTPS则是加密的HTTP,确保数据安全。在Android中,过去常用HttpURLConnection和HttpClient,但HttpClient自Android 6.0起被移除。现在推荐使用支持TLS、流式上传下载、超时配置等特性的HttpsURLConnection进行网络请求。
8 0
|
24天前
解决Error:All flavors must now belong to a named flavor dimension. Learn more at https://d.android.com
解决Error:All flavors must now belong to a named flavor dimension. Learn more at https://d.android.com
21 5
|
1月前
|
Web App开发 前端开发 网络安全
前端分析工具之 Charles 录制 Android/IOS 手机的 https 应用
【2月更文挑战第21天】前端分析工具之 Charles 录制 Android/IOS 手机的 https 应用
50 1
前端分析工具之 Charles 录制 Android/IOS 手机的 https 应用
|
3月前
|
Web App开发 网络协议 Linux
Linux C/C++ 开发(学习笔记十 ):实现http请求器(TCP客户端)
Linux C/C++ 开发(学习笔记十 ):实现http请求器(TCP客户端)
49 0
|
3月前
|
网络协议 安全 API
计算机网络 TCP、RPC、GRPC、HTTP 总结
【1月更文挑战第1天】计算机网络 TCP、RPC、GRPC、HTTP 总结
|
4月前
|
网络协议 JavaScript Unix
TCP实现HTTP服务
TCP实现HTTP服务
29 0