0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Apache HttpClient を使って Transfer-Encoding: chunked を指定してデータを送信

Posted at

Apache HttpClient を使って Transfer-Encoding: chunked を指定してデータを送信するには、HttpEntity をチャンク転送可能なものとして設定すれば実現できます。以下は、Apache HttpClient 4.x を使った例です。

例:チャンク転送で POST する Java コード

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class ChunkedPostExample {
    public static void main(String[] args) throws IOException {
        String url = "http://example.com/upload";

        // データをチャンクで送信するための InputStream
        String data = "これはチャンク転送で送られるデータです。";
        ByteArrayInputStream inputStream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8));

        // InputStreamEntity を使い、chunked 転送を有効化
        InputStreamEntity entity = new InputStreamEntity(inputStream, -1); // -1 は長さ不明 → チャンク扱い
        entity.setChunked(true); // 明示的にチャンク転送を有効に

        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(entity);

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpResponse response = httpClient.execute(httpPost);
            System.out.println("レスポンスコード: " + response.getStatusLine().getStatusCode());
        }
    }
}

補足

InputStreamEntity の第二引数に -1 を指定すると、コンテンツ長が不明として扱われ、チャンク転送が使用されます。

setChunked(true) を明示的に呼ぶことで Transfer-Encoding: chunked が付きます。

Apache HttpClient が自動的に Transfer-Encoding: chunked を設定してくれます。

ポイントまとめ

小さい固定データ(String など)

1チャンクで送られることが多い

InputStream で段階的に提供

複数チャンクに分かれて送信される

setChunked(true) + 長さ不明(-1)

Transfer-Encoding: chunked が使われる

チャンクサイズ制御(HttpClient 側)

明示的には不可(内部バッファサイズに依存)

大きい固定データは複数チャンクになる?

数KB 程度

1チャンクになることが多い

数MB以上

複数チャンクに分割される

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?