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 等效项工作得很好:

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

任何想法我做错了什么?

4

3 回答 3

14

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

http.use_ssl = true

这不是 OPs 问题,但我还是要发布,因为错误消息是相同的,并且该线程是该错误的谷歌热门点击之一。

于 2016-07-19T16:56:03.707 回答
4

你应该指定完整的网址:

req = Net::HTTP::Post.new("https://api.parse.com/1/push")
于 2013-01-29T20:17:18.033 回答
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  

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

于 2016-02-08T11:26:58.113 回答