LoginSignup
12
7

More than 5 years have passed since last update.

Transfer-Encoding: chunked を知らずに生のContentを使用してハマったこと

Posted at

構築済みのWebシステムにおいて別のWebサーバとのサーバ間通信を実装したのですがレスポンス結果を取得したところ正常にjson_decode()できなくてはまりました。。

結論を言うと、Transfer-Encoding: chunkedを知らずにレスポンスから生のContentを取得する関数(getContent())を使用してjsonデコードをしていたのが原因でした。

HTTPレスポンスヘッダにTransfer-Encoding: chunkedがあるとContentがchunk(塊)の連続で送られるらしい。
つまり、下の画像のようなレスポンスになります。(下の例はchunkが1個だけ)

0416-transfer-response.png

それなのに生のContent(dl\r\n{json部分}\r\n0)を抜き出してjsonデコードしたら、そりゃ変換できませんよね。。
どうすればいいのかなと思っていましたが、使用しているフレームワーク(ZF3)のHTTP通信クラスではちゃんとTransfer-Encoding: chunkedを考慮してレスポンスを取得する関数があったのでそちらを使用すれば問題ありませんでした。

Response.php
public function getBody()
{
    $body = (string) $this->getContent();

    $transferEncoding = $this->getHeaders()->get('Transfer-Encoding');

    if (! empty($transferEncoding)) {
        if (strtolower($transferEncoding->getFieldValue()) === 'chunked') {
            $body = $this->decodeChunkedBody($body);  //←★Transfer-Encoding: chunkedの場合ここで変換される
        }
    }

    $contentEncoding = $this->getHeaders()->get('Content-Encoding');

    中略

    return $body;
}
12
7
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
12
7