在 Ruby 中设置请求标头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12161640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting Request Headers in Ruby
提问by Charlie Davies
I have the rest client gem and I am defining a request like this:
我有其余的客户端 gem,我正在定义这样的请求:
url = 'http://someurl'
request = {"data" => data}.to_json
response = RestClient.post(url,request,:content_type => :json, :accept => :json)
However I need to set the HTTP header to something. For example an API key. Which could be done in curl as:
但是我需要将 HTTP 标头设置为某些内容。例如 API 密钥。这可以在 curl 中完成,如下所示:
curl -XHEAD -H x-auth-user: myusername -H x-auth-key: mykey "url"
Whats the best way to do this in ruby? Using this gem? Or can I do it manually to have more control.
在 ruby 中执行此操作的最佳方法是什么?使用这个宝石?或者我可以手动进行以进行更多控制。
回答by Maurício Linhares
The third parameter is the headers hash.
You can do what you want by:
您可以通过以下方式做您想做的事:
response = RestClient.post(
url,
request,
:content_type => :json, :accept => :json, :'x-auth-key' => "mykey")
回答by rrrrong
You can also do this
你也可以这样做
RestClient::Request.execute(
:method => :get or :post,
:url => your_url,
:headers => {key => value}
)
回答by Giorgio Robino
I had the same problem with Rest-Client (1.7.2) I need to put both params and HTTP headers.
我在 Rest-Client (1.7.2) 上遇到了同样的问题,我需要同时放置 params 和 HTTP 标头。
I solved with this syntax:
我用这个语法解决了:
params = {id: id, device: device, status: status}
headers = {myheader: "giorgio"}
RestClient.put url, params, headers
I hate RestClient :-)
我讨厌 RestClient :-)
回答by Serhii Aksiutin
If PUTisn't allowed we can pass it in the header of POST. Headers in bold. This worked for me:
如果PUT不允许,我们可以在POST. 标题以粗体显示。这对我有用:
act_resp = RestClient.post url, req_param, **:content_type => :json, :method => :put**
act_resp = RestClient.post url, req_param, **:content_type => :json, :method => :put**

