Ruby 拆分和解析批处理的 HTTP 响应 (multipart/mixed)
Ruby split and parse batched HTTP Response (multipart/mixed)
我正在使用 GMail API,它允许我获得多个 Gmail objects 的批处理响应。
这以 multipart/mixed HTTP 响应的形式返回,其中一组单独的 HTTP 响应由 header 中定义的边界分隔。
每个 HTTP sub-Responses 是一个 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 objects?
感谢上面的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
我正在使用 GMail API,它允许我获得多个 Gmail objects 的批处理响应。 这以 multipart/mixed HTTP 响应的形式返回,其中一组单独的 HTTP 响应由 header 中定义的边界分隔。 每个 HTTP sub-Responses 是一个 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 objects?
感谢上面的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