PJCHENder 未整理筆記

[Ruby] HTTP request 請求

2019-05-21

[Ruby] HTTP request 請求

@(Ruby on Rails)[Ruby, ajax, http]

發送一般的 GET 請求:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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 請求:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# 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

掃描二維條碼,分享此文章