使用Java 的HTTP 伺服器檔案上傳
簡介
多部分/表單資料編碼
對於混合 POST 內容(二進位和二進位)字元資料),通常使用多部分/表單資料編碼。資料分為多個部分,每個部分都有自己的標頭和正文。Java 解決方案
以下程式碼示範如何使用直接HTTP 連線上傳檔案和參數沒有第三方函式庫:<code class="java">// Parameters String url = "http://example.com/upload"; String param = "value"; // File paths File textFile = new File("/path/to/file.txt"); File binaryFile = new File("/path/to/file.bin"); // Generate unique boundary value String boundary = Long.toHexString(System.currentTimeMillis()); // Create connection URLConnection connection = new URL(url).openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); // OutputStream for writing data try (OutputStream output = connection.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true)) { // Write parameter writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF); writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); writer.append(CRLF).append(param).append(CRLF).flush(); // Write text file writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"textFile\"; filename=\"" + textFile.getName() + "\"").append(CRLF); writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); // Ensure file is saved using this charset writer.append(CRLF).flush(); Files.copy(textFile.toPath(), output); output.flush(); writer.append(CRLF).flush(); // Write binary file writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF); writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF); writer.append("Content-Transfer-Encoding: binary").append(CRLF); writer.append(CRLF).flush(); Files.copy(binaryFile.toPath(), output); output.flush(); writer.append(CRLF).flush(); // End multipart/form-data writer.append("--" + boundary + "--").append(CRLF).flush(); } // Get HTTP response code int responseCode = ((HttpURLConnection) connection).getResponseCode(); System.out.println(responseCode);</code>
附加說明
也請參閱
以上是如何在不依賴第三方程式庫的情況下使用純Java將檔案和參數上傳到HTTP伺服器?的詳細內容。更多資訊請關注PHP中文網其他相關文章!