Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

400 bad request in ruby but not curl

I'm trying to make a https post request in ruby and it works in curl, but I get a 400 bad request in ruby and I'm having trouble figuring out why.

Heres the ruby code:

require 'rubygems'
require 'net/https'
require 'uri'
require 'json'

uri = URI.parse("https://api.parse.com/1/push")
http =  Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE

req = Net::HTTP::Post.new(uri.host)
req['Content-Type'] = "application/json"
req['X-Parse-Application-Id'] = "abc123"
req['X-Parse-REST-API-Key'] = "abc123"

req.body = {:data => {:alert => "sup"}, :channels => ["notifications"]}.to_json

resp = http.start{|http| http.request(req)}

puts resp.inspect

This gives me a #<Net::HTTPBadRequest 400 BAD_REQUEST readbody=true> response.

But the curl equivalent works just fine:

curl -X POST \
  -H "X-Parse-Application-Id: abc123" \
  -H "X-Parse-REST-API-Key: abc123" \
  -H "Content-Type: application/json" \
  -d '{
    "channels": [
      "notifications"
    ],
    "data": {
      "alert": "sup?"
    }
  }' \
  https://api.parse.com/1/push

Any ideas what I'm doing wrong?

like image 767
AdamB Avatar asked Jan 29 '13 19:01

AdamB


2 Answers

For me the problem was not making the request over SSL. Once I set the following line everything worked:

http.use_ssl = true

This wasn't the OPs problem, but I'm posting anyway because the error message is the same and this thread is one of the top google hits for the error.

like image 122
declan Avatar answered Oct 24 '22 00:10

declan


you should specify full url:

req = Net::HTTP::Post.new("https://api.parse.com/1/push")
like image 39
fl00r Avatar answered Oct 24 '22 01:10

fl00r