「労働者が自分の仕事をうまくやりたいなら、まず自分の道具を研ぎ澄まさなければなりません。」 - 孔子、「論語。陸霊公」
表紙 > プログラミング > java.net.URLConnection を使用してファイルと追加パラメータを HTTP サーバーにアップロードするにはどうすればよいですか?

java.net.URLConnection を使用してファイルと追加パラメータを HTTP サーバーにアップロードするにはどうすればよいですか?

2024 年 11 月 7 日に公開
ブラウズ:162

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 エンコーディングを使用します。マルチパート/フォームデータを使用すると、単一の 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