Android编程使用HTTP协议与TCP协议实现上传文件的方法

Android编程使用HTTP协议与TCP协议实现上传文件的方法,第1张

概述本文实例讲述了Android编程使用HTTP协议与TCP协议实现上传文件的方法。分享给大家供大家参考,具体如下:

本文实例讲述了AndroID编程使用http协议与TCP协议实现上传文件的方法。分享给大家供大家参考,具体如下:

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

http协议httpURLConnection

1. 通过URL封装路径打开一个httpURLConnection
2.设置请求方式以及头字段:Content-Type、Content-Length、Host
3.拼接数据发送

示例:

private static final String BOUNDARY = "---------------------------7db1c523809b2";//数据分割线public boolean uploadhttpURLConnection(String username,String password,String path) throws Exception {  //找到sdcard上的文件  file file = new file(Environment.getExternalStorageDirectory(),path);  //仿http协议发送数据方式进行拼接  StringBuilder sb = new StringBuilder();  sb.append("--" + BOUNDARY + "\r\n");  sb.append("Content-disposition: form-data; name=\"username\"" + "\r\n");  sb.append("\r\n");  sb.append(username + "\r\n");  sb.append("--" + BOUNDARY + "\r\n");  sb.append("Content-disposition: form-data; name=\"password\"" + "\r\n");  sb.append("\r\n");  sb.append(password + "\r\n");  sb.append("--" + BOUNDARY + "\r\n");  sb.append("Content-disposition: form-data; name=\"file\"; filename=\"" + path + "\"" + "\r\n");  sb.append("Content-Type: image/pjpeg" + "\r\n");  sb.append("\r\n");  byte[] before = sb.toString().getBytes("UTF-8");  byte[] after = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("UTF-8");  URL url = new URL("http://192.168.1.16:8080/14_Web/servlet/LoginServlet");  httpURLConnection conn = (httpURLConnection) url.openConnection();  conn.setRequestMethod("POST");  conn.setRequestProperty("Content-Type","multipart/form-data; boundary=" + BOUNDARY);  conn.setRequestProperty("Content-Length",String.valueOf(before.length + file.length() + after.length));  conn.setRequestProperty("HOST","192.168.1.16:8080");  conn.setDoOutput(true);  OutputStream out = conn.getoutputStream();  inputStream in = new fileinputStream(file);  out.write(before);  byte[] buf = new byte[1024];  int len;  while ((len = in.read(buf)) != -1)    out.write(buf,len);  out.write(after);  in.close();  out.close();  return conn.getResponseCode() == 200;}

TCP协议Socket

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

示例:

public boolean uploadBySocket(String username,String path) throws Exception {  // 根据path找到SDCard中的文件  file file = new file(Environment.getExternalStorageDirectory(),path);  // 组装表单字段和文件之前的数据  StringBuilder sb = new StringBuilder();  sb.append("--" + BOUNDARY + "\r\n");  sb.append("Content-disposition: form-data; name=\"username\"" + "\r\n");  sb.append("\r\n");  sb.append(username + "\r\n");  sb.append("--" + BOUNDARY + "\r\n");  sb.append("Content-disposition: form-data; name=\"password\"" + "\r\n");  sb.append("\r\n");  sb.append(password + "\r\n");  sb.append("--" + BOUNDARY + "\r\n");  sb.append("Content-disposition: form-data; name=\"file\"; filename=\"" + path + "\"" + "\r\n");  sb.append("Content-Type: image/pjpeg" + "\r\n");  sb.append("\r\n");  // 文件之前的数据  byte[] before = sb.toString().getBytes("UTF-8");  // 文件之后的数据  byte[] after = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("UTF-8");  URL url = new URL("http://192.168.1.199:8080/14_Web/servlet/LoginServlet");  // 由于httpURLConnection中会缓存数据,上传较大文件时会导致内存溢出,所以我们使用Socket传输  Socket socket = new Socket(url.getHost(),url.getPort());  OutputStream out = socket.getoutputStream();  PrintStream ps = new PrintStream(out,true,"UTF-8");  // 写出请求头  ps.println("POST /14_Web/servlet/LoginServlet http/1.1");  ps.println("Content-Type: multipart/form-data; boundary=" + BOUNDARY);  ps.println("Content-Length: " + String.valueOf(before.length + file.length() + after.length));  ps.println("Host: 192.168.1.199:8080");  inputStream in = new fileinputStream(file);  // 写出数据  out.write(before);  byte[] buf = new byte[1024];  int len;  while ((len = in.read(buf)) != -1)    out.write(buf,len);  out.write(after);  in.close();  out.close();  return true;}

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

package cn.test.web.servlet;import java.io.file;import java.io.IOException;import java.util.List;import javax.servlet.servletexception;import javax.servlet.http.httpServlet;import javax.servlet.http.httpServletRequest;import javax.servlet.http.httpServletResponse;import org.apache.commons.fileupload.fileItem;import org.apache.commons.fileupload.fileItemFactory;import org.apache.commons.fileupload.disk.diskfileItemFactory;import org.apache.commons.fileupload.servlet.ServletfileUpload;public class LoginServlet extends httpServlet {  private static final long serialVersionUID = 1L;  @OverrIDe  public voID doGet(httpServletRequest request,httpServletResponse response) throws servletexception,IOException {    doPost(request,response);  }  @OverrIDe  public voID doPost(httpServletRequest request,IOException {    boolean isMultipart = ServletfileUpload.isMultipartContent(request);    if (isMultipart)      try {        fileItemFactory factory = new diskfileItemFactory();        ServletfileUpload upload = new ServletfileUpload(factory);        List<fileItem> items = upload.parseRequest(request);        file dir = new file(request.getSession().getServletContext().getRealPath("/WEB-INF/upload"));        //创建目录        dir.mkdir();        for (fileItem item : items)          if (item.isFormFIEld())            System.out.println(item.getFIEldname() + ": " + item.getString());          else{            item.write(new file(dir,item.getname().substring(item.getname().lastIndexOf("\")+1)));          }      } catch (Exception e) {        e.printstacktrace();      }    else {      System.out.println(request.getmethod());      System.out.println(request.getParameter("username"));      System.out.println(request.getParameter("password"));    }  }}

希望本文所述对大家AndroID程序设计有所帮助。

总结

以上是内存溢出为你收集整理的Android编程使用HTTP协议与TCP协议实现上传文件的方法全部内容,希望文章能够帮你解决Android编程使用HTTP协议与TCP协议实现上传文件的方法所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1141591.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存