我尝试发出HTTP请求以从网站获取数据。
为此,我必须使用自定义标头。
当我向Postman提出请求时,通过添加自定义标题,一切正常。当我删除自定义标头时,收到此错误消息:{"error": "content not found"}
,这是正常的。
我试图在Rails中提出相同的请求。 这是我的代码:
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)
在这种情况下,我添加了自定义标头。但尽管如此,我没有数据,只有这个错误消息:{"error": "content not found"}
,就像我的自定义标头没有被考虑在内一样。我尝试了很多可能而没有成功。
有人可以帮助我吗?我的想法已经不多了。
提前感谢您的建议。
致以最诚挚的问候,
修改
以下是我对法拉第的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
这是服务器响应:
回应:#https://www.itqi.com/api/master-descriptor> @ request =#@ request_headers = {" User-Agent" =>" Faraday v0.12.2"," Content-Type" =>&#34 ; application / json"," itqi-key" =>" **********************&#34 ;} @ ssl =#@ response = #response_headers = {" date" =>" Wed,13 Dec 2017 08:25:53 GMT"," server&# 34; =>" Apache / 2.4.10(Debian)","内容长度" =>" 29","连接&# 34; =>"关闭","内容类型" =>" application / json; charset = UTF-8"} @ status = 404 @reason_phrase =" Not Found">>
始终存在同样的问题:(
************************解决方案********************** ****
经过一些研究,似乎在Rails中标题键区分大小写。因此,为了解决这个问题,我不得不强迫Rails将它们放在小写中。没有它,Rails会系统地将它们资本化。
有我的解决方案:
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
答案 0 :(得分:0)
您的代码与http://ruby-doc.org/stdlib-2.0.0/libdoc/net/http/rdoc/Net/HTTP.html#label-Setting+Headers上的示例不同。
但是如果你改用法拉第(https://github.com/lostisland/faraday),我建议你会更开心。
答案 1 :(得分:0)
我在同一个帖子客户端中找到了这个问题的答案,在这里我可以找到工作查询的示例。邮递员给我JavaScript提取的工作代码:
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)