Setting Request Headers in Ruby

2019-03-09 00:54发布

I have the rest client gem and I am defining a request like this:

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:

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 rest
4条回答
\"骚年 ilove
2楼-- · 2019-03-09 01:31

I had the same problem with Rest-Client (1.7.2) I need to put both params and HTTP headers.

I solved with this syntax:

params = {id: id, device: device, status: status}
headers = {myheader: "giorgio"}

RestClient.put url, params, headers

I hate RestClient :-)

查看更多
劳资没心,怎么记你
3楼-- · 2019-03-09 01:34

You can also do this

RestClient::Request.execute(
   :method => :get or :post,
   :url => your_url,
   :headers => {key => value}
)
查看更多
一纸荒年 Trace。
4楼-- · 2019-03-09 01:48

If PUT isn't allowed we can pass it in the header of POST. Headers in bold. This worked for me:

act_resp = RestClient.post url, req_param, **:content_type => :json, :method => :put**

查看更多
霸刀☆藐视天下
5楼-- · 2019-03-09 01:49

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")
查看更多
登录 后发表回答