How to invoke HTTP POST method over SSL in ruby?

前端 未结 4 1426
深忆病人
深忆病人 2020-12-02 16:56

So here\'s the request using curl:

curl -XPOST -H content-type:application/json -d \"{\\\"credentials\\\":{\\\"username\\\":\\\"username\\\",\\\"key\\\":\\\"         


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-02 17:56

    All others are too long here is a ONE LINER:

    Net::HTTP.start('auth.api.rackspacecloud.com', :use_ssl => true).post(
          '/v1.1/auth', {:credentials => {:username => "username",:key => "key"}}.to_json,
          initheader={'Content-Type' => 'application/json'}
        )
    

    * to_json needs require 'json'


    OR if you want to

    • NOT verify the hosts
    • be more readable
    • ensure the connection is closed once you're done

    then:

    ssl_opts={:use_ssl => true, :verify_mode => OpenSSL::SSL::VERIFY_NONE}
    Net::HTTP.start('auth.api.rackspacecloud.com', ssl_opts) { |secure_connection|
      secure_connection.post(
          '/v1.1/auth', {:credentials => {:username => "username",:key => "key"}}.to_json,
          initheader={'Content-Type' => 'application/json'}
        )
    }
    

    In case it's tough to remember what params go where:

    • SSL options are per connection so you specify them while opening the connection.
    • You can reuse the connection for multiple REST calls to same base url. Think of thread safety of course.
    • Header is a "request header" and hence specified per request. I.e. in calls to get/post/patch/....
    • HTTP.start(): Creates a new Net::HTTP object, then additionally opens the TCP connection and HTTP session.
    • HTTP.new(): Creates a new Net::HTTP object without opening a TCP connection or HTTP session.

提交回复
热议问题