简体   繁体   中英

Error while doing HTTP Request

I am using Typhoeus gem to execute HTTP requests in my rails Application. The request is as follows.

 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)

here while executing this the auth_token has been converted to auth%5Ftoken=abcd. Actually my API expecting the parameter auth_token. Because of this API is not allowing to access it. It's throwing unauthorized error. Please help me to solve this problem. Thanks in Advance.

I corrected that issue with to_query. Actually to_query is parsing the actual data to the API

Here is an example using RestClient that shows a correct submission of the data, I expect Typhoeus not to be different:

 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]
 }  

Here is the payload, as expected:

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

Using 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]

As expected, this is the payload of the request. So your code is good!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM