我正在尝试访问Julia中以下URL的数据。当我转到“ https://api.stackexchange.com/2.2/questions?order=desc&sort=activity&tagged=Julia&site=stackoverflow ” 时,我可以看到似乎是JSON对象的内容。但是,当我尝试在r
下面打印结果时,它会给我一个无法正确渲染的文本,或者如果JSON.print
显示的话,会显示一堆随机数。
如何使用Julia获得在浏览器中看到的相同内容(最好以文本形式)。
r = HTTP.request("GET", "https://api.stackexchange.com/2.2/questions?order=desc&sort=activity&tagged=Julia&site=stackoverflow"; verbose=3)
fredrikekre.. 7
响应主体使用压缩gzip
,如您在Content-Encoding
标头中所见:
julia> using HTTP julia> r = HTTP.request("GET", "https://api.stackexchange.com/2.2/questions?order=desc&sort=activity&tagged=Julia&site=stackoverflow") HTTP.Messages.Response: """ HTTP/1.1 200 OK Cache-Control: private Content-Type: application/json; charset=utf-8 Content-Encoding: gzip <---- [...]
所以你必须用例如解压缩它CodecZlib
:
julia> using CodecZlib julia> compressed = HTTP.payload(r); julia> decompressed = transcode(GzipDecompressor, compressed);
在这里,您可以创建一个String
(例如String(decompressed)
)或使用例如JSON
包对其进行解析:
julia> using JSON julia> json = JSON.parse(IOBuffer(decompressed)) Dict{String,Any} with 4 entries: "items" => Any[Dict{String,Any}("link"=>"/sf/ask/17360801/","view_count"=>5,"creation_date"=… "quota_max" => 300 "quota_remaining" => 297 "has_more" => true
(另请参阅https://github.com/JuliaWeb/HTTP.jl/issues/256)
响应主体使用压缩gzip
,如您在Content-Encoding
标头中所见:
julia> using HTTP julia> r = HTTP.request("GET", "https://api.stackexchange.com/2.2/questions?order=desc&sort=activity&tagged=Julia&site=stackoverflow") HTTP.Messages.Response: """ HTTP/1.1 200 OK Cache-Control: private Content-Type: application/json; charset=utf-8 Content-Encoding: gzip <---- [...]
所以你必须用例如解压缩它CodecZlib
:
julia> using CodecZlib julia> compressed = HTTP.payload(r); julia> decompressed = transcode(GzipDecompressor, compressed);
在这里,您可以创建一个String
(例如String(decompressed)
)或使用例如JSON
包对其进行解析:
julia> using JSON julia> json = JSON.parse(IOBuffer(decompressed)) Dict{String,Any} with 4 entries: "items" => Any[Dict{String,Any}("link"=>"/sf/ask/17360801/","view_count"=>5,"creation_date"=… "quota_max" => 300 "quota_remaining" => 297 "has_more" => true
(另请参阅https://github.com/JuliaWeb/HTTP.jl/issues/256)