【问题标题】:How to run this curl command using Net:HTTP如何使用 Net:HTTP 运行这个 curl 命令
【发布时间】:2014-10-25 11:21:48
【问题描述】:

所以我需要通过 https 运行这个命令:

curl -u "{user_id}:{license_key}" \
      "https://geoip.maxmind.com/geoip/v2.1/city/me?pretty"

我认为这可能是可能的

http://www.ruby-doc.org/stdlib-2.1.3/libdoc/net/http/rdoc/Net/HTTP.html#class-Net::HTTP-label-HTTPS

有没有办法做到这一点?

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    我从您的示例中假设您正在尝试进行基本身份验证。对于通过 SSL 使用基本身份验证的 net/http get 请求,您可以执行以下操作:

    require 'uri'
    require 'net/http'
    
    uri = URI("https://geoip.maxmind.com/geoip/v2.1/city/me?pretty")
    uri.basic_auth 'user_id', 'license_key'
    
    res = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => true) { |http| 
      http.request(req) 
    }
    puts res.body
    

    我个人觉得所有这些设置都很麻烦;您还可以在标准库选项中选择用户友好的 gem。以下是使用httparty 时相同请求的外观:

    require 'httparty'
    auth = { :username => 'user_id', :password => 'license_key' }
    res = HTTParty.get("https://geoip.maxmind.com/geoip/v2.1/city/me?pretty", 
      :basic_auth => auth)
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-10
    • 2018-03-03
    • 2017-08-04
    • 1970-01-01
    • 2022-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多