為了將附加參數的檔案從Java 用戶端上傳到HTTP 伺服器,讓我們探索一下一個場景及其解決方案。
想像一下您想要將一個檔案和一個名為「使用者名稱」的參數傳遞到伺服器。如何使用帶有 multipart/form-data 編碼的 POST 請求來實現此目的?
為了讓事情簡單明了,讓我們避開第三方函式庫並依賴 Java 的內建工具。
<code class="java">import java.io.File; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.URLConnection; import java.nio.file.Files; import java.nio.file.Path; import java.util.Scanner; public class HttpFileUploadWithParameters { private static final String BOUNDARY = Long.toHexString(System.currentTimeMillis()); private static final String CRLF = "\r\n"; private static final String CHARSET = "UTF-8"; public static void main(String[] args) throws Exception { String url = "http://example.com/upload"; File file = new File("/path/to/file.txt"); String parameter = "value"; 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, CHARSET), true)) { // Write parameter writer.append("--" + BOUNDARY).append(CRLF); writer.append("Content-Disposition: form-data; name=\"parameter\"").append(CRLF); writer.append("Content-Type: text/plain; charset=" + CHARSET).append(CRLF); writer.append(CRLF).append(parameter).append(CRLF).flush(); // Write file writer.append("--" + BOUNDARY).append(CRLF); writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"").append(CRLF); writer.append("Content-Type: application/octet-stream").append(CRLF); writer.append(CRLF).flush(); Files.copy(file.toPath(), output); output.flush(); // Important before continuing with writer! writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary. // End of multipart/form-data. writer.append("--" + BOUNDARY + "--").append(CRLF).flush(); } // Request is lazily fired whenever you need to obtain information about response. int responseCode = ((java.net.HttpURLConnection) connection).getResponseCode(); System.out.println(responseCode); // Should be 200 } }</code>
以上是如何在沒有第三方函式庫的情況下使用「multipart/form-data」編碼從 Java 用戶端上傳帶有附加參數的檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!