执行HTTP请求时出错

时间:2014-04-11 11:03:08

标签: ruby-on-rails ruby ruby-on-rails-3 http typhoeus

我正在使用Typhoeus gem在我的rails应用程序中执行HTTP请求。请求如下。

 data = {"auth_token"=>"abcd" ,"employee" => {"method" => "add_employee"}}
 header =  { "Content-Type" => "application/json","Accept"=>"application/json"}
 request = Typhoeus::Request.post("www.example.com",:body=> data.to_json,:headers => header)

执行此操作时,auth_token已转换为auth%5Ftoken = abcd。实际上我的API期望参数auth_token。因为此API不允许访问它。这是未经授权的错误。请帮我解决这个问题。在此先感谢。

2 个答案:

答案 0 :(得分:0)

我用to_query纠正了这个问题。实际上to_query正在将实际数据解析为API

答案 1 :(得分:-1)

以下是使用RestClient显示正确提交数据的示例,我希望Typhoeus不会有所不同:

 data = {"auth_token"=>"abcd" ,"employee" => {"method" => "add_employee"}}
 header =  { "Content-Type" => "application/json","Accept"=>"application/json"}
 RestClient.post("www.example.com", data.to_json, header){ |response, request, result| 
       puts "PAYLOAD:"+request.args[:payload]
 }  

这是有效载荷,如预期的那样:

 PAYLOAD: "{\"auth_token\":\"abcd\",\"employee\":{\"method\":\"add_employee\"}}"

使用Typhoeus:

 data = {"auth_token"=>"abcd" ,"employee" => {"method" => "add_employee"}}
 header =  { "Content-Type" => "application/json","Accept"=>"application/json"}
 request = Typhoeus::Request.post("www.example.com",:body=> data.to_json,:headers => header)
 request.request.original_options[:body]

正如所料,这是请求的有效负载。所以你的代码很好!

 "{\"auth_token\":\"abcd\",\"employee\":{\"method\":\"add_employee\"}}"