Ruby分割和解析批处理HTTP响应(多部分/混合)

3
我正在使用Gmail API,它允许我获取多个Gmail对象的批处理响应。这以multipart/mixed 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对象?

1
之前回答过一个非常相似的问题。也许你可以在那里得到一些启示! - Tholle
1个回答

4
感谢上面的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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接