示例:
public boolean uploadBySocket(String username, String password, 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, 0, len); out.write(after); in.close(); out.close(); return true; }Android分别使用HTTP协议和TCP协议实现上传文件(2)
内容版权声明:除非注明,否则皆为本站原创文章。