Android programming uses HTTP protocol and TCP protocol to upload files
- 2020-12-10 00:52:26
- OfStack
This article illustrates the method of Android programming using HTTP and TCP protocols to upload files. To share for your reference, the details are as follows:
There are two ways for Android to upload files: HttpURLConnection based on Http protocol and Socket based on TCP protocol. The difference between the two methods is that with HttpURLConnection uploads have an internal caching mechanism, which can cause memory leaks if you upload a large file. If you upload in TCP, Socket will solve this problem.
HttpURLConnection HTTP agreement
1. Open one HttpURLConnection via the URL package path
2. Set the request mode and header fields: ES23en-ES24en, ES25en-ES26en, Host
3. Splicing data to send
Example:
private static final String BOUNDARY = "---------------------------7db1c523809b2";// Data divider
public boolean uploadHttpURLConnection(String username, String password, String path) throws Exception {
// find sdcard The file on the
File file = new File(Environment.getExternalStorageDirectory(), path);
// imitation Http The protocol sends data to be spliced
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, 0, len);
out.write(after);
in.close();
out.close();
return conn.getResponseCode() == 200;
}
Socket TCP agreement
1. We can use Socket to send TCP request and send the uploaded data in sections
Example:
public boolean uploadBySocket(String username, String password, String path) throws Exception {
// According to the path find SDCard The files in the
File file = new File(Environment.getExternalStorageDirectory(), path);
// Assemble the data before the form fields and files
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");
// The data before the file
byte[] before = sb.toString().getBytes("UTF-8");
// The data after the file
byte[] after = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("UTF-8");
URL url = new URL("http://192.168.1.199:8080/14_Web/servlet/LoginServlet");
// Due to the HttpURLConnection Cache data , Uploading large files can cause memory leaks , So we use Socket transmission
Socket socket = new Socket(url.getHost(), url.getPort());
OutputStream out = socket.getOutputStream();
PrintStream ps = new PrintStream(out, true, "UTF-8");
// Write the request header
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);
// Write the data
out.write(before);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) != -1)
out.write(buf, 0, len);
out.write(after);
in.close();
out.close();
return true;
}
Set up the server and complete the upload function
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, HttpServletResponse response) throws ServletException, 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"));
// Create a directory
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"));
}
}
}
I hope this article has been helpful in Android programming.