我有純 Ruby 應用程式,我想在其中創建對外部 API 的請求。為此,我使用標準的 Ruby Net::HTTP,如下所示:
require 'net/http'
require 'uri'
class Api
BASE_URI = 'https://staging.test.com'
WORKFLOW = 'tests'
QUIZ_PATH = "/v3/accounts/workflows/#{WORKFLOW}/conversations"
def initialize(payload:)
@payload = payload
end
def post_quiz
handle_response(Net::HTTP.post_form("#{BASE_URI}#{QUIZ_PATH}", options))
end
attr_reader :payload
private
def options
{
basic_auth: basic_auth,
body: payload.to_json,
headers: headers
}
end
def basic_auth
{
username: Settings.ln_username,
password: Settings.ln_password
}
end
def headers
{
'User-Agent' => 'Mozilla/5.0',
'Accept-Language' => 'en-US,en;q=0.5',
'Content-Type' => 'application/json'
}
end
def handle_response(response)
return response.body if response.success?
end
end
但是我收到了一個錯誤而不是回應:
NoMethodError: #String:0x00007f80eef9e6f8 的未定義方法`user' 你的意思是?極好的
/Users/usr/.rvm/rubies/ruby-2.7.0/lib/ruby/2.7.0/net/http.rb:527:in `post_form'
我那里沒有任何用戶,這是什么?
uj5u.com熱心網友回復:
Net::HTTP.post_form 用于發送 FormData 對 - 它不是您想要發送的 JSON,它甚至不允許您發送標頭(您實際上是將它們放在請求正文中!)。
如果要發送帶有 HTTP 基本身份驗證和自定義標頭和 JSON 正文的 POST 請求,則需要手動創建請求物件:
require 'net/http'
require 'uri'
class Api
BASE_URI = 'https://staging.test.com'
WORKFLOW = 'tests'
QUIZ_PATH = "/v3/accounts/workflows/#{WORKFLOW}/conversations"
attr_reader :payload
def initialize(payload:)
@payload = payload
end
def post_quiz
url = URI.join(BASE_URI, QUIZ_PATH)
request = Net::HTTP::Post.new(url, headers)
request.basic_auth = Settings.ln_username, Settings.ln_password
request.body = @payload.to_json
# open a connection to the server
response = Net::HTTP.start(url.hostname, url.port, use_ssl: true) do |http|
http.request(request)
end
handle_response(response)
end
private
def headers
{
'User-Agent' => 'Mozilla/5.0',
'Accept-Language' => 'en-US,en;q=0.5',
'Content-Type' => 'application/json'
}
end
# How to respond from an API client is a whole topic in itself but a tuple or hash might
# be a better choice as it lets consumers decide what to do with the response and handle stuff like logging
# errors
def handle_response(response)
# Net::HTTP doesn't have a success? method - you're confusing it with HTTParty
case response
when Net::HTTPSuccess, Net::HTTPCreated
response.body
else
false
end
end
end
uj5u.com熱心網友回復:
這是引發錯誤的源代碼:
def HTTP.post_form(url, params)
req = Post.new(url)
req.form_data = params
>> req.basic_auth url.user, url.password if url.user
start(url.hostname, url.port,
:use_ssl => url.scheme == 'https' ) {|http|
http.request(req)
}
end
從檔案:
post_form(網址,引數)
將 HTML 表單資料發布到指定的 URI 物件。表單資料必須作為從字串到字串的哈希映射提供。
這意味著Net::HTTP.post_form(URI("#{BASE_URI}#{QUIZ_PATH}"), options)修復它。您當前正在發送一個字串作為 url 而不是 URI。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/374986.html
標籤:红宝石
