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

Mary-Kate Olsen
リリース: 2024-10-25 03:02:30
オリジナル
182 人が閲覧しました

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 リクエストでバイナリ データ (ファイル) と文字データ (パラメータ) を混在させることができます。

コード例:

<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>
ログイン後にコピー

追加の注意事項:

  • 各マルチパート リクエストには必ず一意の境界値を指定してください。
  • ファイルは、Content-Type ヘッダーの送信時に指定された文字セット内にある必要があります。 .
  • Apache Commons HttpComponents Client はプロセスをさらに合理化できますが、必須ではありません。

参照:

  • [使用方法] HTTP リクエストを起動して処理するための java.net.URLConnection](https://docs.oracle.com/javase/tutorial/networking/urls/creating-urls.html)

以上がjava.net.URLConnection を使用してファイルと追加パラメータを HTTP サーバーにアップロードするにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:php.cn
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!