使用HTTP 請求上傳檔案
將檔案上傳到HTTP 伺服器,同時提交其他參數、java.net.URLConnection 和multipart/通常採用形式資料編碼。以下是流程的細分:
Multipart/Form-Data 編碼
Multipart/form-data 專為組合二進位(例如檔案)的POST 請求而設計和字元資料(例如參數)。編碼涉及將請求正文分為多個部分,每個部分以邊界字串開頭。
範例程式碼
<code class="java">import java.io.File; import java.io.OutputStream; import java.io.PrintWriter; import java.net.URLConnection; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; public class FileUpload { public static void main(String[] args) throws Exception { String url = "http://example.com/upload"; String param = "value"; File textFile = new File("/path/to/file.txt"); File binaryFile = new File("/path/to/file.bin"); String boundary = Long.toHexString(System.currentTimeMillis()); URLConnection connection = new URL(url).openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); try (OutputStream output = connection.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8), true)) { // Send parameter writer.append("--" + boundary).append("\r\n"); writer.append("Content-Disposition: form-data; name=\"param\"").append("\r\n"); writer.append("Content-Type: text/plain; charset=" + StandardCharsets.UTF_8).append("\r\n"); writer.append("\r\n").append(param).append("\r\n").flush(); // Send text file writer.append("--" + boundary).append("\r\n"); writer.append("Content-Disposition: form-data; name=\"textFile\"; filename=\"" + textFile.getName() + "\"").append("\r\n"); writer.append("Content-Type: text/plain; charset=" + StandardCharsets.UTF_8).append("\r\n"); writer.append("\r\n").flush(); Files.copy(textFile.toPath(), output); output.flush(); writer.append("\r\n").flush(); // Send binary file writer.append("--" + boundary).append("\r\n"); writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append("\r\n"); writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())).append("\r\n"); writer.append("Content-Transfer-Encoding: binary").append("\r\n"); writer.append("\r\n").flush(); Files.copy(binaryFile.toPath(), output); output.flush(); writer.append("\r\n").flush(); // End of multipart/form-data writer.append("--" + boundary + "--").append("\r\n").flush(); } int responseCode = ((HttpURLConnection) connection).getResponseCode(); System.out.println("Response Code: " + responseCode); } }</code>
附加註解
以上是如何使用 java.net.URLConnection 和 multipart/form-data 編碼上傳附加參數的檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!