Question

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?

Was it helpful?

Solution 2

you should specify full url:

req = Net::HTTP::Post.new("https://api.parse.com/1/push")

OTHER TIPS

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.

def get_job(job_name)

        puts "Posting job #{job_name} to get test update order service"

        get_job_xml ="<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns=\"http://os.uk/Test/GetUpdateOrders/1.0\">
       <soapenv:Header/>
       <soapenv:Body>
          <ns:GetTestUpdateOrdersReq>
             <ContractGroup>abc</ContractGroup>
             <ProductID>myproduct</ProductID>
             <Reference>#{job_name}</Reference>
          </ns:GetTestUpdateOrdersReq>
       </soapenv:Body>
    </soapenv:Envelope>"

        @http = Net::HTTP.new(@server, @port)


        request = Net::HTTP::Post.new(('/XISOAPAdapter/MessageServlet?senderParty=&senderService=faceNamespace=http://myco.uk/Test/GetUpdateOrders/1.0'), initheader = {'Content-Type' => 'text/xml'})
        request.basic_auth(@username, @password)
        request.content_type='text/xml'
        request.body = get_job_xml
        response = @http.request(request)


      end  

I have defined my method like this and its working.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top