如何向 Rails 应用程序发送 http post 请求以获取 json 响应
对于 GET 请求,其:-
response = Typhoeus::Request.get("http://localhost:3000/users/1.json?oauth_token=12")
这会完美返回 Json 响应。
对于 Post 请求:-
response = Typhoeus::Request.post("http://localhost:3000/users/1.json?oauth_token=12",:params => {'[user][city]' => params[:location]})
不起作用...
这将返回路由错误。
更新:--
对于登录,此 api post 调用正在工作。.
response = Typhoeus::Request.post(API_SERVER_ADDRESS + "user_sessions.json" + API_OAUTH_TOKEN, :params => {'[user_session][email]' => params[:email], '[user_session][password]' =>params[:password]})
在路由中,它的
resources :users
以及 Web http 请求工作得很好。.
更新
例如,来自 Rails 日志的 http 请求是:--
Parameters: {"commit"=>"Update", "authenticity_token"=>"8nvzCd0GF9IxjMcTfHOMJTPnycVPNIENMoMff8w4qAI=", "utf8"=>"✓", "id"=>"1", "user"=>{ "city"=>"abc"}}
现在我想要发送同样类型的请求..
For GET request its:-
response = Typhoeus::Request.get("http://localhost:3000/users/1.json?oauth_token=12")
This returns Json response perfectly.
for Post request:-
response = Typhoeus::Request.post("http://localhost:3000/users/1.json?oauth_token=12",:params => {'[user][city]' => params[:location]})
is not working...
This is returning routing error.
Update:--
FOr login this api post call is working..
response = Typhoeus::Request.post(API_SERVER_ADDRESS + "user_sessions.json" + API_OAUTH_TOKEN, :params => {'[user_session][email]' => params[:email], '[user_session][password]' =>params[:password]})
In routes its
resources :users
and also web http request is working perfectly fine..
UPDATE
For example http request from rails log is:--
Parameters: {"commit"=>"Update", "authenticity_token"=>"8nvzCd0GF9IxjMcTfHOMJTPnycVPNIENMoMff8w4qAI=", "utf8"=>"✓", "id"=>"1", "user"=>{ "city"=>"abc"}}
Now i want to sent same kind of request..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
:params 参数应该是你的 parms 的哈希值,意思是键值对,所以可能是这样的:
...或者类似的东西 - 无论 parms 是什么,无论值是什么。我认为,您的原始内容并不能转化为您想做的事情的有意义的哈希值。
另外,请检查您的路由,以确保您尝试执行的操作已正确路由。
The :params parameter should be a hash of your parms, meaning key-value pairs, so maybe something like this:
...or somesuch - whatever the parms are, whatever the values are. Your original doesn't translate into a meaningful hash for what you are wanting to do, I think.
Also, check your routing to make sure that what you are trying to do is properly routed.
解决方案
这是来自 this 的
Here is the solution
From this
确保您已在
routes.rb
文件中声明了单独的POST
路由。即使 URL 相同,不同的 HTTP 方法也需要不同的路由。使用
resources :users
默认情况下会提供以下内容:Make sure you have declared a separate
POST
route in yourroutes.rb
file. Even if the URLs are the same, different HTTP methods require different routes.Using
resources :users
gives you the following by default: