简体   繁体   English

HTTP 请求适用于 Postman 但不适用于 Rails

[英]HTTP Request works with Postman but not in Rails

I'm trying to make a HTTP Request to get data from a website.我正在尝试发出 HTTP 请求以从网站获取数据。 To do that, I have to use a custom header.为此,我必须使用自定义标头。 When I make a request with Postman, by adding well the custom header, everything works fine.当我向 Postman 发出请求时,通过添加自定义标头,一切正常。 When I remove the custom header, I get this error message : {"error": "content not found"} , which is normal.当我删除自定义标头时,我收到此错误消息: {"error": "content not found"} ,这是正常的。

I tried to make the same request in Rails.我试图在 Rails 中提出相同的请求。 This is my code :这是我的代码:

uri = URI.parse("https://www.itqi.com/api/master-descriptor")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
req = Net::HTTP::Get.new(uri.path)
req["itqi-key"] = '************************'
response = http.request(req)

In this case, I added the custom header.在这种情况下,我添加了自定义标头。 But in despite this, I got no data, only this error message : {"error": "content not found"} , like if my custom header was not taken into account.但尽管如此,我没有得到任何数据,只有这个错误消息: {"error": "content not found"} ,就像没有考虑我的自定义标头一样。 I tried many possibilities without success.我尝试了很多可能性都没有成功。

Is there somebody who can help me ?有人可以帮助我吗? I'm running out of ideas.我的想法不多了。

Thanks in advance for your advices.预先感谢您的建议。

Best regards,最好的问候,

EDIT编辑

Here is my https request with Faraday :这是我对法拉第的 https 请求:

conn = Faraday.new(:url => 'https://www.itqi.com', :ssl => {:verify => false})
response = conn.get do |req|
    req.url '/api/master-descriptor'
    req.headers['Content-Type'] = 'application/json'
    req.headers['itqi-key'] = '********************'
end

And here is the server response :这是服务器响应:

RESPONSE: #https://www.itqi.com/api/master-descriptor> @request=# @request_headers={"User-Agent"=>"Faraday v0.12.2", "Content-Type"=>"application/json", "itqi-key"=>"**********************"} @ssl=# @response=# @response_headers={"date"=>"Wed, 13 Dec 2017 08:25:53 GMT", "server"=>"Apache/2.4.10 (Debian)", "content-length"=>"29", "connection"=>"close", "content-type"=>"application/json; charset=UTF-8"} @status=404 @reason_phrase="Not Found">>响应:#https://www.itqi.com/api/master-descriptor> @request=# @request_headers={"User-Agent"=>"Faraday v0.12.2", "Content-Type"=>"application /json", "itqi-key"=>"**********************"} @ssl=# @response=# @response_headers={"date “=>”2017 年 12 月 13 日星期三 08:25:53 GMT”,“服务器”=>“Apache/2.4.10(Debian)”,“内容长度”=>“29”,“连接”=>“ close", "content-type"=>"application/json; charset=UTF-8"} @status=404 @reason_phrase="未找到">>

Always the same problem :(总是同样的问题:(

************************ SOLUTION ************************** ************************ 解决方案 ************************ *

After some research, it seems to be that header keys are case sensitive in Rails.经过一番研究,似乎在 Rails 中标题键区分大小写。 So, to resolve the problem, I had to force Rails to put them in lowercase.所以,为了解决这个问题,我不得不强制 Rails 把它们变成小写。 Without that, Rails systematically capitalized them.没有这些,Rails 系统地将它们大写。

There is my solution :有我的解决方案:

conn = Faraday.new(url: 'https://www.itqi.com', ssl: {verify: false}) do |conn|
  conn.request :json
  conn.response :json, :content_type => /\bjson$/
  conn.adapter Faraday.default_adapter
end
response = conn.get do |req|
  req.url '/api/master-descriptor'
  itqi_key = CaseSensitiveString.new('itqi-key')
  req.headers[itqi_key] = '************************'
end

class CaseSensitiveString < String
  def downcase
     self
  end
  def capitalize
     self
  end

  def to_s
    self
  end
end

Your code does not look like the example on http://ruby-doc.org/stdlib-2.0.0/libdoc/net/http/rdoc/Net/HTTP.html#label-Setting+Headers .您的代码看起来不像http://ruby-doc.org/stdlib-2.0.0/libdoc/net/http/rdoc/Net/HTTP.html#label-Setting+Headers上的示例。

But I suggest you'll be happier if you switch to Faraday ( https://github.com/lostisland/faraday ).但我建议你如果切换到法拉第( https://github.com/lostisland/faraday )会更快乐。

The answer on this question i found in the same post client, where i can found examples of working query.我在同一个帖子客户端中找到了关于这个问题的答案,在那里我可以找到工作查询的示例。 Postman give me working code for javascript fetch:邮递员给我 javascript fetch 的工作代码:

  const options: RequestOptions = {
    credentials: 'same-origin',
    headers: {
      'Accept': 'application/json',
    },
    method: method as string,
    mode: 'no-cors',
  }
  if ([RestMethods.post, RestMethods.put].includes(method as RestMethods)) {
    // isn't working:
    // options.headers['Content-Type'] = 'application/json'
    // options.body = JSON.stringify(paramsSnakeCased)
    const urlencoded = new URLSearchParams();
    Object.keys(paramsSnakeCased).forEach((key: string) => {
      urlencoded.append(key, paramsSnakeCased[key])
    })
    options.body = urlencoded
    options.headers['Content-Type'] = 'application/x-www-form-urlencoded'
  }

  fetch(url, options).then(resolve)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM