[英]How to pass raw-data into post request using HTTParty (or any other way in ruby)
我必須在 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)
在所有情況下,響應都表示沒有傳遞任何數據
最終,這對我有用:
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)
你可以試試這個
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 用作 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.