2015-11-02 72 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