跳至主要内容

[Ruby] HTTP request 請求

發送一般的 GET 請求:

begin
uri = URI("http://localhost:8080/api/v1/languages?limit=-1")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = uri.scheme == 'https'
req = Net::HTTP::Get.new(uri, {
'Content-Type' => 'application/json',
'Version' => '1'
})
res = http.request(req) # 發送請求

if res.kind_of? Net::HTTPSuccess
res_body = JSON.parse(res.body) # 取得回應,並解析 JSON
languages = res_body['data']['languages']
end
rescue
flash.now[:alert] = 'Failed to get option for languages, please try again later.'
end

發送 POST 請求:

# app/controllers/pages_controller.rb
def tester_create
@tester = Tester.new(tester_params)

if @tester.valid?
begin
uri = URI("#{Rails.application.config.api_url}/tester/create")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = uri.scheme == 'https'
req = Net::HTTP::Post.new(uri.path, {
'Content-Type' =>'application/json',
'Version' => '1'
})
req.body = {
name: @tester.name,
email: @tester.email,
}.to_json

res = http.request(req)
if res.kind_of? Net::HTTPSuccess
redirect_to tester_confirmation_url, notice: 'Thank you! We will contact you as soon as possible.'
else
# 當請求不是 HTTPSuccess 時
res_body = JSON.parse(res.body)
flash.now[:alert] = 'Failed to register, please try again later.'
render :tester
end
rescue
# 當 HTTP Request 有錯誤回應時
flash.now[:alert] = 'Failed to register, please try again later.'
render :tester
end
else
flash.now[:notice] = 'Please make sure you have filled in all fields in the form.'
render :tester
end
end