http POST error - ruby-on-rails

I'm trying to send the xml to another webserver through Restclient's http POST request.This is the code :
response = RestClient.post 'https://secure.rowebooks.co.uk/testorders/orders.aspx', :content_type => "text/xml", :myfile => File.read("#{Rails.root}/public/shared/#{#book}.xml")
But I'm getting this error
ERROR 2 Data at the root level is invalid. Line 1, position 1.ERROR3 Object reference not set to an instance of an object.
I've been told that I am receiving that error because the XML file is not in the content of the call. It must be in the content. I have no idea what does this mean.
Any suggestion / clue will be greatly appreciated.
Thanks

You should be doing it like this:
response = RestClient.post( 'https://secure.rowebooks.co.uk/testorders/orders.aspx',
File.read("#{Rails.root}/public/shared/#{#book}.xml"), 'Content-Type' => 'text/xml' )

Related

how to access this kind of hash

I am using RestClient to make a post request and i made it so i an error response back so i can print those error messages in console
i tried the following per the restclient gem documentation
begin
response = RestClient.post base_uri, params.to_json, content_type: 'application/json', accept: 'application/json'
rescue RestClient::ExceptionWithResponse => err
error = err.response
p "this is the error response #{error}"
end
when i print err.response i get the following
"this is the error response {\"error\":{\"message\":\"An active access token must be used to query information about the current us
er.\",\"type\":\"OAuthException\",\"code\":2500,\"fbtrace_id\":\"HTzmJ0CcIfd\"}}"
how do i access the message in the above hash to display it in console?
tried
p "this is the error response #{error.message}"
and it gives me "Bad request" - have no idea where it gets that
If you're just looking to output it:
error = JSON.load(err.response)
puts error['error']['message']
You can always format it a bit better:
puts '[Code %d %s] %s' % [
error['error']['code'],
error['error']['type'],
error['error']['message']
]
Note that using puts inside of a Rails process is not going to work very well. You might want to use Rails.logger.debug instead.
The response you received is in JSON. You'll need to decode the JSON first and then interact with the data. Personally, I like MultiJson for this:
begin
response = RestClient.post base_uri, params.to_json, content_type: 'application/json', accept: 'application/json'
rescue RestClient::ExceptionWithResponse => err
error = MultiJson.load(err.response)
p "this is the error response #{error[:message]}"
end

Rails RestClient POST request failing with "400 Bad Request"

Looking at the docs there aren't any good examples of how to make a POST request. I need to make a POST request with a auth_token parameter and get a response back:
response = RestClient::Request.execute(method: :post,
url: 'http://api.example.com/starthere',
payload: '{"auth_token" : "my_token"}',
headers: {"Content-Type" => "text/plain"}
)
400 bad request error:
RestClient::BadRequest: 400 Bad Request
from /Users/me/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/rest-client-1.8.0/lib/restclient/abstract_response.rb:74:in `return!'
from /Users/me/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/rest-client-1.8.0/lib/restclient/request.rb:495:in `process_result'
from /Users/me/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/rest-client-1.8.0/lib/me/request.rb:421:in `block in transmit'
Any good examples how to make a POST request using RestClient?
EDIT:
This is how I make the request in the model:
def start
response = RestClient::Request.execute(method: :post,
url: 'http://api.example.com/starthere',
payload: '{"auth_token" : "my_token"}',
headers: {"Content-Type" => "text/plain"}
)
puts response
end
Try using a hash like this:
def start
url= 'http://api.example.com/starthere'
params = {auth_token: 'my_token'}.to_json
response = RestClient.post url, params
puts response
end
If you just want to replicate the curl request:
response = RestClient::Request.execute(method: :post, url: 'http://api.example.com/starthere', payload: {"auth_token" => "my_token"})
Both Curl and RestClient defaults to the same content type (application/x-www-form-urlencoded) when posting data the this format.
In case you land here having the same Issue, Just know that this is a common error that happens when your environment variables are not "set".
I put this in quotes because you might have set it but not available in the current terminal session!
You can check if the ENV KEY is available with:
printenv <yourenvkey>
if you get nothing then it means you need to re-add it or just put it in your bash files
FYI: Putting my ENV variables in my ~/.bash_profile fixed it

The content type 'application/x-www-form-urlencoded' is not supported in Ruby on Rails

So I'm just trying to make a simple post request using httpclient in RoR.
I'm going through a proxy, doing ntlm authentication with the server ( I can make GET requests without a problem).
Now when I try and do a post request, I get the error mentioned in the title...
proxy = ENV['HTTP_PROXY']
client=HTTPClient.new(proxy)
client.set_auth(nil,user,pass)
body= [{'Content-Type' => 'application/atom+xml, :content => ...}]
res = client.post('url',body)
puts res.body
How am i getting this error when I clearly specify the header as atom+xml..?
You should use
res = client.post('url',
:body => "...body content...",
:header => {'Content-Type' => 'application/atom+xml'})

bad URI(is not URI?): {"message":"d64","type":"success"}

Am using httparty to send API request, I want to get output response after i sent request,
url = HTTParty.post("https://example.com/api/sendhttp.php",
:query => { :authkey => "authkeyvalue",
:mobiles => mobileNos,
:message => messages,
:sender => "senderid",
:route => "routeid",
:response => 'json'
})
response = HTTParty.get(url)
puts response.body, response.code, response.message, response.headers.inspect
But when i run above code it throws bad URI(is not URI?): {"message":"d64","type":"success"} error. How to solve it and get the response?
This looks like you are running a POST to https://example.com/api/sendhttp.php with JSON format, this succeeds, and you're getting a response of:
{"message":"d64","type":"success"}
So your url variable now contains {"message":"d64","type":"success"}, which is clearly not a valid URL, so when you try to do a GET on it, you get an error. You've already got a response from the first POST, you should perhaps parse this? You don't need to do
response = HTTPParty.get(url)
unless you're expecting a second GET request to a URL which is returned by the first.

Rails - Sending image using Faraday

I'm trying to make a request to an API sending an image and some other data, and getting the response. That's my code:
file = "assets/images/test.jpg"
conn = Faraday.new(:url => "api_url" ) do |faraday|
faraday.request :multipart
end
payload = { :profile_pic => Faraday::UploadIO.new(file, 'image/jpeg') }
conn.post "/test", payload
My first problem is that I'm always getting the following error:
Errno::ENOENT (No such file or directory - assets/images/test.png)
I've tried all the paths I could imagine. Where should be saved the image in directories to be found by Faraday?
The second question is about the response, how can I get the response and handle it?
The third one is that, I haven't understand what's the utility of the first parameter of the last call:
conn.post "/hello", payload
I've written "/hello" but don't have any idea about what's the real usage.
And the last one. Could I send a raw image saved in a variable instead of sending a path to Faraday?
EDIT
Now it's working, this is the solution:
Be aware that url must be only until .com, the rest of the path must go on conn.post like this example /v1/search.
c.adapter :net_http was needed too.
Message response is correctly handled in json variable.
Solution:
url = 'http://url.com'
file = Rails.root.to_s + "/app/assets/images/test.jpg"
conn = Faraday.new(:url => url ) do |c|
c.request :multipart
c.adapter :net_http
end
payload = { :image => Faraday::UploadIO.new(file, 'image/jpeg'), :token => token}
response = conn.post '/v1/search', payload
json = JSON.parse response.body
You should try this for your first question :
file = Rails.root.to_s + "/app/assets/images/test.jpg"
For your third question, the first parameters allows you to construct the right URL from the base "api_url". Please see the example from the Readme.
## POST ##
conn.post '/nigiri', { :name => 'Maguro' } # POST "name=maguro" to http://sushi.com/nigiri

Resources