【问题标题】:Why am I getting Net::HTTPBadResponse with this Ruby code?为什么我用这个 Ruby 代码得到 Net::HTTPBadResponse?
【发布时间】:2016-03-20 21:43:12
【问题描述】:

我要通过法拉第提出请求。我使用 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$/

假网页代码

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: "{"

【问题讨论】:

    标签: ruby faraday


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-15
      • 1970-01-01
      相关资源
      最近更新 更多