[英]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:我必须在 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.我们通常使用 HTTParty 发出 http 请求,但我在尝试将原始数据传递到请求中时遇到了一些问题。 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.当您将 HTTParty 用作 OOP 中的 mixin 而不是过程代码时,HTTParty 真的很出色。
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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.