【问题标题】:400 bad request in ruby but not curl400 ruby​​ 中的错误请求,但不是 curl
【发布时间】:2013-01-29 19:41:27
【问题描述】:

我正在尝试在 ruby​​ 中发出 https 发布请求,它在 curl 中有效,但我在 ruby​​ 中收到 400 错误请求,我无法找出原因。

这是 ruby​​ 代码:

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

任何想法我做错了什么?

【问题讨论】:

    标签: ruby curl net-http ruby-1.8.7


    【解决方案1】:

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

    http.use_ssl = true
    

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

    【讨论】:

      【解决方案2】:

      您应该指定完整的网址:

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

      【讨论】:

        【解决方案3】:
        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  
        

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-03-04
          • 1970-01-01
          • 1970-01-01
          • 2014-03-05
          • 1970-01-01
          • 2023-03-11
          • 2012-12-02
          • 1970-01-01
          相关资源
          最近更新 更多