开发者

How to send a http post request to a rails app to get json response

开发者 https://www.devze.com 2023-03-15 05:02 出处:网络
For GET request its:- response = Typhoeus::Request.get(\"http://localhost:3000/users/1.json?oauth_token=12\")

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 log开发者_StackOverflow中文版in 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..


The :params parameter should be a hash of your parms, meaning key-value pairs, so maybe something like this:

response = Typhoeus::Request.post("http://localhost:3000/users/1.json?oauth_token=12",:params => {:user => 'u', :city => 'c', :location => 'l'})

...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.


Here is the solution

From this

 response = Typhoeus::Request.put(API_SERVER_ADDRESS + "users/" +user_id + ".json" ,:params => {:oauth_token=>'12', :user=>{:city => params[:location]}})


Make sure you have declared a separate POST route in your routes.rb file. Even if the URLs are the same, different HTTP methods require different routes.

Using resources :users gives you the following by default:

GET     /users/new        # new
POST    /users            # create
GET     /users/:id        # show
GET     /users/:id/edit   # edit
PUT     /users/:id        # update
DELETE  /users/:id        # destroy
0

精彩评论

暂无评论...
验证码 换一张
取 消