简体   繁体   中英

How to pass raw-data into post request using HTTParty (or any other way in ruby)

I have to make this request in rails 6:

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

We usually use HTTParty to make http requests, but i faced some problems trying to pass raw data into the request. I've already tried:

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)

And in all cases, the response says that no data was passed

Eventually, this worked for me:

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)

You can try with this

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

HTTParty really shines when you use it as a mixin in OOP instead of proceedural code.

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM