使用 Java 中的附加參數將檔案上傳到 HTTP 伺服器
將檔案上傳到 HTTP 伺服器是許多應用程式的常見需求。但是,有時也需要隨文件一起傳遞附加參數。這是一個允許您在不使用外部程式庫的情況下發送檔案和參數的解決方案:
java.net.URLConnection 和Multipart/Form-Data
傳送檔案和參數,您將利用java.net.URLConnection 並採用multipart/form-data 編碼。 Multipart/form-data 可讓您在單一 HTTP 請求中混合二進位資料(檔案)和字元資料(參數)。
範例程式碼:
<code class="java">String url = "http://example.com/upload"; String charset = "UTF-8"; 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()); String CRLF = "\r\n"; 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); ) { // Send normal param. 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(); // Send 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); writer.append(CRLF).flush(); Files.copy(textFile.toPath(), output); output.flush(); writer.append(CRLF).flush(); // Send 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 of multipart/form-data. writer.append("--" + boundary + "--").append(CRLF).flush(); } // Request is lazily fired whenever you need to obtain information about response. int responseCode = ((HttpURLConnection) connection).getResponseCode(); System.out.println(responseCode); </code>
附加說明:
參考:
以上是如何使用 java.net.URLConnection 將檔案和附加參數上傳到 HTTP 伺服器?的詳細內容。更多資訊請關注PHP中文網其他相關文章!