在 Java 中使用附加參數將檔案上傳到 HTTP 伺服器
將檔案上傳到 HTTP 伺服器是許多應用程式的常見需求。但是,有時也需要隨文件一起傳遞附加參數。這是一個允許您在不使用外部庫的情況下發送文件和參數的解決方案:
java.net.URLConnection 和Multipart/Form-Data
傳送檔案和參數,您將利用java.net.URLConnection 並採用multipart/form-data 編碼。 Multipart/form-data 可讓您在單一 HTTP 請求中混合二進位資料(檔案)和字元資料(參數)。
範例程式碼:
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);
附加說明:
參考:
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3