为什么我使用这个Ruby代码获取Net :: HTTPBadResponse?

时间:2016-03-20 21:43:12

标签: ruby faraday

我要通过法拉第提出请求。我使用FakeWeb来存根请求。

法拉第代码

  middleware =  [
  Faraday::Request::UrlEncoded,
  AirbrakeAPI::Middleware::RaiseResponseError,
  FaradayMiddleware::Mashify,
  FaradayMiddleware::ParseXml,
  AirbrakeAPI::Middleware::ScrubResponse,
  AirbrakeAPI::Middleware::RaiseServerError]

  @connection ||= Faraday.new(default_options.deep_merge(connection_options)) do |builder|
    middleware.each { |mw| builder.use *mw }
    builder.adapter :net_http
    builder.response :json, :content_type => /\bjson$/

fakeweb代码

DEFAULTS = {:content_type => "application/json; charset=utf-8", :status => ["200", "OK"]}

def fixture_request(verb, url, file)
  FakeWeb.register_uri(verb, url, DEFAULTS.merge(:response => File.join(File.dirname(__FILE__), 'fixtures', file)))
end

fixture_request :get, "http://example.com/notices.json", 'notices.json'

notices.json文件

HTTP/1.1 200 OK
Content-Type: application/json
Date: Sun, 20 Mar 2016 05:24:04 GMT
Transfer-Encoding: chunked
{
  "notices": [
    {
      "id": "1",
      "projectId": 1,
      "groupId": "1696170",
      "createdAt": "2014-10-22T03:00:00.407Z"
    },
    {
      "id": "2",
      "projectId": 1,
      "groupId": "1234",
      "createdAt": "2014-10-22T03:00:00.407Z"
    }
  ],
  "count": 2
}

我得到的错误:

# Net::HTTPBadResponse:
     #   wrong header line format

在notices.json文件中,如果我删除1-4行(第1行= HTTP / 1.1 200 OK),那么我仍然会收到此错误:

# Net::HTTPBadResponse:
     #   wrong status line: "{"

1 个答案:

答案 0 :(得分:1)

您的notices.json不是有效的HTTP。请注意标题之后和正文之前的CRLF(新行):https://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html