」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何使用 java.net.URLConnection 將檔案和附加參數上傳到 HTTP 伺服器?

如何使用 java.net.URLConnection 將檔案和附加參數上傳到 HTTP 伺服器?

發佈於2024-11-07
瀏覽:200

How to upload files and additional parameters to an HTTP server using java.net.URLConnection?

在 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); 

附加說明:

  • 確保為每個多部分請求提供唯一的邊界值。
  • 檔案必須採用指定的字元集發送 Content-Type 標頭。
  • Apache Commons HttpComponents Client 可以進一步簡化這個過程,但這不是必要的。

參考:

  • [使用java.net.URLConnection 觸發和處理HTTP 請求](https://docs.oracle.com/ javase/tutorial/networking/urls/creating-urls.html)
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3