2015-11-02 100 views
3

我正在使用GMail API,它可以获取多个Gmail对象的批量响应。 这是以多部分/混合HTTP响应的形式返回的,其中包含一组单独的HTTP响应,它们由标题中定义的边界分隔。 每个HTTP子响应都是JSON格式。Ruby分割和解析批量HTTP响应(多部分/混合)

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

回答非常[类似的问题](http://stackoverflow.com/questions/33289711/parsing-gmail-batch-response-in-javascript/33300582 #33300582)一会儿回来。也许你可以在那里得到一些启发! – Tholle

回答

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