ホームページ  >  記事  >  Java  >  サードパーティのライブラリに依存せずに Pure Java を使用してファイルとパラメータを HTTP サーバーにアップロードするにはどうすればよいですか?

サードパーティのライブラリに依存せずに Pure Java を使用してファイルとパラメータを HTTP サーバーにアップロードするにはどうすればよいですか?

Patricia Arquette
Patricia Arquetteオリジナル
2024-10-25 04:11:29785ブラウズ

How can I upload files and parameters to an HTTP server using pure Java without relying on third-party libraries?

Java を使用した HTTP サーバー ファイルのアップロード

概要

この記事では、HTTP サーバーへのファイルのアップロードについて説明します。 Java クライアントからの HTTP サーバー。私たちは、POST リクエスト内でパラメーターとファイルを組み合わせる、シンプルで無料のソリューションを提供することを目指しています。

マルチパート/フォーム データ エンコーディング

混合 POST コンテンツ (バイナリと文字データ)、通常はマルチパート/フォームデータ エンコーディングが使用されます。データはセクションに分割されており、それぞれに独自のヘッダーと本文があります。

Java ソリューション

次のコードは、直接 HTTP 接続を使用してファイルとパラメーターをアップロードする方法を示しています。サードパーティのライブラリを使用しない場合:

<code class="java">// Parameters
String url = "http://example.com/upload";
String param = "value";

// File paths
File textFile = new File("/path/to/file.txt");
File binaryFile = new File("/path/to/file.bin");

// Generate unique boundary value
String boundary = Long.toHexString(System.currentTimeMillis());

// Create connection
URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

// OutputStream for writing data
try (OutputStream output = connection.getOutputStream();
     PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true)) {

    // Write parameter
    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();

    // Write 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); // Ensure file is saved using this charset
    writer.append(CRLF).flush();
    Files.copy(textFile.toPath(), output);
    output.flush(); 
    writer.append(CRLF).flush();

    // Write 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 multipart/form-data
    writer.append("--" + boundary + "--").append(CRLF).flush();
}

// Get HTTP response code
int responseCode = ((HttpURLConnection) connection).getResponseCode();
System.out.println(responseCode);</code>

追加メモ

  • Files.copy は Java 7 で導入されました。古いバージョンの場合は、FileUtils.copyFile を使用してください。
  • Apache Commons HttpComponents Client は、このプロセスを簡素化する一般的なサードパーティ ライブラリです。
  • Apache Commons FileUpload は、ファイルのアップロードを処理するためにサーバー側で使用されます。

関連項目

  • [java.net.URLConnection を使用した HTTP リクエストの起動と処理](リソースへのリンク)

以上がサードパーティのライブラリに依存せずに Pure Java を使用してファイルとパラメータを HTTP サーバーにアップロードするにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。