CORDEA blog

Android applications engineer

Factor で http-request の response body が byte-array になった時

あるサービスの API レスポンスで body が byte-array になったので調べた

結論

charset が指定されていなくて byte-array になったら適切な形で decode する
utf-8 なら

http-get drop body>> utf8 decode json> .

詳細

サーバー側で charset が指定されていない場合は content-encoding が binary になるので
response body は byte-array になります.

例えば,以下のようなコードを書いた場合

"http://example.com" http-get drop .
charset が指定されていない場合
T{ response
    { version "1.1" }
    { code 200 }
    { message "OK " }
    { header
        H{
            { "connection" "close" }
            { "date" "Sun, 29 Jan 2017 08:48:16 GMT" }
            { "content-length" "12" }
            { "x-content-type-options" "nosniff" }
            { "server" "WEBrick/1.3.1 (Ruby/2.4.0/2016-12-24)" }
            { "content-type" "application/json" }
        }
    }
    { cookies { } }
    { content-type "application/json" }
    { content-encoding binary }
    { body B{ 123 34 115 116 97 116 117 115 34 58 49 125 } }
}
charset が指定されている場合
T{ response
    { version "1.1" }
    { code 200 }
    { message "OK " }
    { header
        H{
            { "connection" "close" }
            { "date" "Sun, 29 Jan 2017 08:47:25 GMT" }
            { "content-length" "12" }
            { "x-content-type-options" "nosniff" }
            { "server" "WEBrick/1.3.1 (Ruby/2.4.0/2016-12-24)" }
            { "content-type" "application/json; charset=utf-8" }
        }
    }
    { cookies { } }
    { content-type "application/json" }
    { content-charset "utf-8" }
    { content-encoding utf8 }
    { body "{\"status\":1}" }
}

charset が指定されていないと,いざ body 取って json として読み込もうとした場合に

Generic word json> does not define a method for the byte-array class. 

で怒られます.

こういう場合は

"http://example.com" http-get drop body>> utf8 decode json> .

のように decode して読み込む.

以上,charset 大事という話でした.