【问题标题】:How to pass raw-data into post request using HTTParty (or any other way in ruby)如何使用 HTTParty(或 ruby​​ 中的任何其他方式)将原始数据传递到 post 请求中
【发布时间】:2020-12-14 11:02:02
【问题描述】:

我必须在 rails 6 中提出这个请求:

curl --location --request POST 'https://www.example.com/auth' \
--header 'Content-Type: application/json' \
--data-raw '{
    "Username": "my_username",
    "Password": "my_password"
}'

我们通常使用 HTTParty 发出 http 请求,但我在尝试将原始数据传递到请求中时遇到了一些问题。 我已经试过了:

url = 'https://www.example.com/auth'
auth_data = { Username: 'my_username', Password: 'my_password' }
headers = {'Content-Type' => 'application/json'}

HTTParty.post(url, data: auth_data, headers: headers)
HTTParty.post(url, data: auth_data.to_json, headers: headers)
HTTParty.post(url, data: [auth_data].to_json, headers: headers)
HTTParty.post(url, body: auth_data, headers: headers)

在所有情况下,响应都表示没有传递任何数据

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-6 httparty


    【解决方案1】:

    最终,这对我有用:

    uri = URI.parse('https://www.example.com/auth')
    auth_data = { Username: 'my_username', Password: 'my_password' }
    headers = {'Content-Type' => 'application/json'}
    
    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true
    http.post(uri.path, auth_data.to_json, headers)
    

    【讨论】:

      【解决方案2】:

      你可以试试这个

      require 'net/http'
      
      uri = URI('https://www.example.com/auth')
      Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
        req = Net::HTTP::Post.new(uri)
        req['Content-Type'] = 'application/json'
        req.set_form_data({Username: "my_username", Password: "my_password"})
        response = http.request req # Net::HTTPResponse object
      end
      

      【讨论】:

      • 我得到“此资源不支持请求实体的媒体类型 'application/x-www-form-urlencoded'”。无论如何,我已经找到了另一个解决方案,但感谢您的建议!
      【解决方案3】:

      当您将 HTTParty 用作 OOP 中的 mixin 而不是过程代码时,它真的很出色。

      class AuthenticationClient
        include Httparty
        format :json
        base_uri 'http://example.com'
      
        def authenticate(username:, password:)
          post 'auth', {
            username: username,
            password: password
          }
        end
      end
      
      AuthenticationClient.new.authenticate(username: 'Max', password: 'p4ssword')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-25
        • 1970-01-01
        相关资源
        最近更新 更多