400红宝石的坏请求但不卷曲

时间:2013-01-29 19:41:28

标签: ruby curl net-http ruby-1.8.7

我正在尝试在ruby中发布https发布请求并且它在curl中工作,但我在ruby中收到了400个错误请求,而我无法弄清楚原因。

继承红宝石代码:

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

这给了我一个#<Net::HTTPBadRequest 400 BAD_REQUEST readbody=true>回复。

但卷曲等效工作正常:

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

任何想法我做错了什么?

3 个答案:

答案 0 :(得分:7)

对我来说问题是没有通过SSL发出请求。一旦我设置了以下行,一切正常:

http.use_ssl = true

这不是OP的问题,但我还是发帖,因为错误信息是相同的,这个帖子是该错误的热门谷歌点击之一。

答案 1 :(得分:4)

你应该指定完整网址:

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

答案 2 :(得分:0)

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  

我已经定义了这样的方法及其工作方式。