我使用GMail API,可以让我获得多个Gmail对象的批量响应。 这以多部分/混合HTTP响应的形式返回,其中一组单独的HTTP响应由标头中定义的边界分隔。 每个HTTP子响应都是JSON格式。
即
result.response.response_headers = {...
"content-type"=>"multipart/mixed; boundary=batch_abcdefg"...
}
result.response.body = "----batch_abcdefg
<the response header>
{some JSON}
--batch_abcdefg
<another response header>
{some JSON}
--batch_abcdefg--"
是否有一个库或一种简单的方法将这些响应从字符串转换为一组单独的HTTP响应或JSON对象?
答案 0 :(得分:3)
感谢上面的Tholle ......
def parse_batch_response(response, json=true)
# Not the same delimiter in the response as we specify ourselves in the request,
# so we have to extract it.
# This should give us exactly what we need.
delimiter = response.split("\r\n")[0].strip
parts = response.split(delimiter)
# The first part will always be an empty string. Just remove it.
parts.shift
# The last part will be the "--". Just remove it.
parts.pop
if json
# collects the response body as json
results = parts.map{ |part| JSON.parse(part.match(/{.+}/m).to_s)}
else
# collates the separate responses as strings so you can do something with them
# e.g. you need the response codes
results = parts.map{ |part| part}
end
result
end