【问题标题】:Setting Request Headers in Ruby在 Ruby 中设置请求标头
【发布时间】:2012-08-28 14:34:40
【问题描述】:

我有其余的客户端 gem,我正在定义这样的请求:

url = 'http://someurl'
request =  {"data" => data}.to_json
response = RestClient.post(url,request,:content_type => :json, :accept => :json)

但是我需要将 HTTP 标头设置为某些内容。例如 API 密钥。这可以在 curl 中完成:

curl -XHEAD -H x-auth-user: myusername -H x-auth-key: mykey "url"

在 ruby​​ 中执行此操作的最佳方法是什么?使用这个宝石?或者我可以手动操作以获得更多控制权。

【问题讨论】:

    标签: ruby rest


    【解决方案1】:

    The third parameter is the headers hash

    你可以做你想做的事:

    response = RestClient.post( 
      url, 
      request,
      :content_type => :json, :accept => :json, :'x-auth-key' => "mykey")
    

    【讨论】:

    【解决方案2】:

    你也可以这样做

    RestClient::Request.execute(
       :method => :get or :post,
       :url => your_url,
       :headers => {key => value}
    )
    

    【讨论】:

    • 非常有帮助,谢谢,在文档中没有看到 :headers => {}
    【解决方案3】:

    我在使用 Rest-Client (1.7.2) 时遇到了同样的问题,我需要同时放置参数和 HTTP 标头。

    我用这个语法解决了:

    params = {id: id, device: device, status: status}
    headers = {myheader: "giorgio"}
    
    RestClient.put url, params, headers
    

    我讨厌 RestClient :-)

    【讨论】:

      【解决方案4】:

      如果不允许PUT,我们可以在POST 的标头中传递它。粗体标题。这对我有用:

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

      【讨论】:

        猜你喜欢
        • 2013-05-25
        • 2020-12-22
        • 2023-04-03
        • 2013-03-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-24
        相关资源
        最近更新 更多