Http協議格式——socket實現http檔案上傳
阿新 • • 發佈:2019-01-26
RT,做專案中有時候會遇到服務端為web服務,但在客戶端需要通過socket來與之互動的情況,這時候就需要用到socket來模擬http傳輸。。自己做過一次抓包分析,但是沒把結果記錄下來,後來做專案中需要用到,才百度了一下,現在把百度到的結果記錄下來……
程式碼如下,具體結構自己稍微動下腦子就能看出來吧。。。
private static final String BOUNDARY = "---------------------------7db1c523809b2";// 資料分割線 private static final String DIRECTORY = "e:\\"; /** * * @see java Socket 模擬 http上傳檔案 * * @see 多檔案上傳 */ public static void upload(String name, List<File> files) throws Exception { // 表單欄位和檔案的資料 StringBuilder sb = new StringBuilder(); sb.append("\r\n\r\n--" + BOUNDARY + "\r\n"); sb.append("Content-Disposition: form-data; name=\"name\"" + "\r\n"); sb.append("\r\n"); sb.append(name + "\r\n"); sb.append("--" + BOUNDARY + "\r\n"); sb.append("Content-Disposition: form-data; name=\"age\"" + "\r\n"); sb.append("\r\n"); sb.append(30 + "\r\n"); // 檔案之前的資料 byte[] before = sb.toString().getBytes("UTF-8"); // 檔案之後的資料 byte[] after = ("--" + BOUNDARY + "--\r\n").getBytes("UTF-8"); String uploadURL = "/PosAxis/servlet/UploadServlet"; //上傳檔案的Servlet URL url = new URL("http://192.168.210.251:8080"+uploadURL); Socket socket = new Socket(url.getHost(), url.getPort()); socket.setSoTimeout(30000); socket.setKeepAlive(true); socket.setSendBufferSize(262144); socket.setReceiveBufferSize(262144); OutputStream out = socket.getOutputStream(); PrintStream ps = new PrintStream(out, true, "UTF-8"); long length = 0; int blen = 0; for (int i = 0; i < files.size(); i++) { length += files.get(i).length(); sb = new StringBuilder(); sb.append("--" + BOUNDARY + "\r\n"); sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + files.get(i).getName() + "\"" + "\r\n"); sb.append("Content-Type: image/pjpeg" + "\r\n"); sb.append("\r\n"); blen += sb.toString().getBytes("UTF-8").length; }//請求頭 StringBuffer header = new StringBuffer(); header.append("POST "+uploadURL+" HTTP/1.1\r\n"); header.append("Host: 192.168.210.251:8080\r\n"); header.append("Accept: */*\r\n"); header.append("Accept-Language: zh-cn\r\n"); header.append("Accept-Charset: utf-8\r\n"); header.append("Content-Type: multipart/form-data; boundary=" + BOUNDARY + "\r\n"); header.append("Content-Length: " + String.valueOf(before.length + blen + length + after.length)); ps.print(header); out.write(before); byte[] buf = new byte[2048]; int len; for (int i = 0; i < files.size(); i++) { sb = new StringBuilder(); sb.append("--" + BOUNDARY + "\r\n"); sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + files.get(i).getName() + "\"" + "\r\n"); sb.append("Content-Type: image/pjpeg" + "\r\n"); sb.append("\r\n"); out.write(sb.toString().getBytes("UTF-8")); InputStream in = new FileInputStream(files.get(i)); while ((len = in.read(buf)) != -1) { out.write(buf, 0, len);out.flush(); in.close(); out.write("\r\n".getBytes("UTF-8")); } out.write(after); out.flush(); out.close(); }