使用HTTP POST 要求將檔案從Java 用戶端上傳到伺服器時,很常見想要在文件中包含其他參數。這是一個簡單而高效的解決方案,無需外部庫:
利用java.net.URLConnection 建立HTTP 請求並將其設置為多部分錶單數據,這是一種流行的編碼格式,用於處理二進制和文字資料。這是一個包含附加參數param 和檔案textFile 和binaryFile 的範例:
<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"); 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 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 boundary writer.append("--" + boundary + "--").append(CRLF).flush(); }</code>
設定請求後,您可以觸發它並檢索回應程式碼:
<code class="java">((HttpURLConnection) connection).getResponseCode();</code>
了解更多進階場景或簡化流程,請考慮使用第三方函式庫,例如Apache Commons HttpComponents Client。
以上是如何使用Java的`URLConnection`上傳檔案和附加參數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!