【问题标题】:Net::HTTPBadResponse (wrong header line format)Net::HTTPBadResponse(错误的标题行格式)
【发布时间】:2016-02-29 05:31:00
【问题描述】:

请帮助我理解,我做错了什么? 我需要从我的 Rails 应用程序向 api 发出 POST 请求,我首先尝试使用 gem“法拉第”,然后使用“net/http”。来自服务器的响应相同。帐户创建,但出现错误:

Net::HTTPBadResponse(错误的标题行格式)

class Connect
 require 'uri'
 require 'net/http'
 require 'net/https'
 require 'faraday'

 def initialize(email, password, account)
   @base_url = "https://example.com"
   @client_id = ENV["client_id"]
   @client_secret = ENV["client_secret"]
   @email = email
   @password = password
   @account = account
 end

 # method with net/http
 def create_account

   @toSend = {
     first_name: @account[:first_name],
     last_name: @account[:last_name],
     client_id: @client_id,
     client_secret: @client_secret,
     email: @email,
     password: @password
   }.to_json

  uri = URI.parse("#{@base_url}/endclient/api/account")
  https = Net::HTTP.new(uri.host,uri.port)
  https.use_ssl = true
  req = Net::HTTP::Post.new(
    uri.path,
    initheader = {
                   'Content-Type' =>'application/json',
                   'Accept' =>'application/json'
    }
  )
  req.body = "#{@toSend}"
  res = https.request(req)
 end

 # faraday method
 def make_account

  conn = Faraday.new(:url => "#{@base_url}") do |faraday|
    faraday.response :logger                  
    faraday.adapter  Faraday.default_adapter
  end

  params = { first_name: @account[:first_name],
    last_name: @account[:last_name],
    client_id: @client_id,
    client_secret: @client_secret,
    email: @email,
    password: @password
   }.to_json

  response = conn.post do |req|
    req.url '/endclient/api/account'
    req.headers['Content-Type'] = 'application/json'
    req.headers['Accept'] = 'application/json'
    req.body = params
  end
 end
end

通过Postman成功完成此请求,因此api的端点正在工作。

请帮助我了解标题有什么问题? 提前致谢!

更新:

这可能有问题吗?

Cannot render console with content type application/jsonAllowed content  types: [#<Mime::Type:0x00000003661658 @synonyms=["application/xhtml+xml"], @symbol=:html, @string="text/html">, #<Mime::Type:0x00000003660fc8 @synonyms=[], @symbol=:text, @string="text/plain">, #<Mime::Type:0x0000000365ca68 @synonyms=[], @symbol=:url_encoded_form, @string="application/x-www-form-urlencoded">]

【问题讨论】:

  • 对于您的 net/http 方法,请尝试使用 req.body = @toSend.to_query 而不是 req.body = "#{@toSend}"。让我知道它是否有效。
  • @HarryBomrah,谢谢你的回答,我试过了,它给了我错误ArgumentError (wrong number of arguments (0 for 1)
  • 哪一行?你有什么改变吗?
  • @HarryBomrah 在这行req.body = @toSend.to_query,不,什么都不做。
  • 从您的@toSend = {...}.to_json 中删除to_json

标签: ruby-on-rails net-http faraday


【解决方案1】:

如果您想要一个可以轻松混合到类/模块中的 http 库,我会推荐 httparty 而不是 Faraday 或只是简单的旧 Net::HTTP

require 'httparty' # Requires go at the top of the file. Not in class body.

class MyApiClient
  include HTTParty
  base_uri 'test.example.com'
  # Tells Httparty to send JSON for all requests.
  format :json 

  # @see https://robots.thoughtbot.com/ruby-2-keyword-arguments
  def initialize(client_id: ENV["client_id"], client_secret: ENV["client_secret"])
    @options = { 
      body: { 
        client_id: client_id, 
        client_secret: client_secret
      } 
    }
  end

  # @return [HTTParty::Response]
  def create_account(first_name:, last_name:, email:, password:)
    # ActiveSupport method that creates a copy so that we don't 
    # alter the instance options as a side effect.
    opts = @options.deep_dup 
    opts[:body].merge!(
      email: email, 
      password: password,
      first_name: first_name,
      last_name: last_name
    )
    self.class.post('/endclient/api/account', opts)
  end
end

好消息是httparty 将完成所有工作,解析与 JSON 之间的参数并发送正确的标头。它还负责构建 URI 的枯燥工作。

注意方法签名略有不同:

client = MyApiClient.new
response = client.create_account(
  first_name: 'John',
  last_name: 'Doe',
  email: 'john.doe@example.com',
  password: 'abcd1234'
)

【讨论】:

  • 附带说明,您的 API 可能不应该在每个请求中获取客户端 ID 和密钥。客户应首先进行身份验证并交易一个令牌,然后随每个请求发送该令牌。但是如何构建基于令牌的身份验证有点超出了这里的范围。
  • 感谢您的回答。 HTTP派对很好。我们发现了错误,这是来自第三方 API nginx 的错误标头。
【解决方案2】:

API 端出现问题,标头符号错误。

【讨论】:

    猜你喜欢
    • 2014-06-21
    • 1970-01-01
    • 1970-01-01
    • 2014-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多