標籤:地址 code 發送資料 https roo style useragent 源碼 hub
如果一個 URL 要求POST資料是 JSON格式的, 那我們要怎麼發送資料呢?
第一種:
HTTP::Request
上一篇說到, 發送 POST 資料, 可以:
1. $ua.post(url, %data)
2. $request.add-form-data(%data) $ua.request($request)
在這裡, 無論是第一種方法還是第二種方法, 裡面所發送的 %data 都會自動編碼。
JSON也是一種字串格式, 這兩種方法要求%data為一個hash, 那就說明這兩種方法不能實現發送JSON。
HTTP::Request 其實還有一種方法, 叫做:
add-content
些方法接受一個字串的參數, 我們可以用這種方式提交JSON:
> my $request = HTTP::Request.new(POST=>‘http://localhost/‘)
添加 JSON 字串:
> $request.content(Any)> %data = :user<root>, :password<root>{password => root, user => root}> $request.add-content(to-json(%data))Nil> $request.content{ "password" : "root", "user" : "root" }>
我這裡用了 to-json (這方法在模組 JSON::Tiny中)把一個%data轉化為一個 JSON字串再傳入$request中。
之後再請求就行了:
my $html = $ua.request($request)
我們可以列印出請求參數看一下是不是真的發送了JSON格式字串:
> $html.request.StrPOST / HTTP/1.1Host: localhostContent-Length: 40Connection: close{ "password" : "root", "user" : "root" }>
可以看到, 是發送了 JSON 格式的字串資料。
基實我們只要發送一個 JSON的字串就行了, 我上面的代碼, 只是為了方便, 把一個 %data 轉化成了字串, 其實我們可以定義一個 JSON 格式的字串, 再 add-content 添加, 最後發送即可, 如下:
先建立一個字串:
> my $post_string = ‘{"password":"root", "user":"root"}‘
添加進request對象並請求:
> $request.add-content($post_string)Nil> $html = $ua.request($request)
最後列印請求參數是否正確:
> $html.request.StrPOST / HTTP/1.1Host: localhostContent-Length: 34Connection: close{"password":"root", "user":"root"}>
可以看到, 一樣是能正常發送的。
除了用 HTTP::Request 發送 JSON 請求外, PERL6還有一個模組:
WWW
這個模組可以接收字串格式的POST資料, 也就是JSON了:
multi jpost($url where URI:D|Str:D, *%form);multi jpost($url where URI:D|Str:D, %headers, *%form);multi jpost($url where URI:D|Str:D, Str:D $form-body, *%headers);say jpost ‘https://httpbin.org/post?meow=moo‘, :72foo, :bar<?>;say jpost ‘https://httpbin.org/post?meow=moo‘, %(Content-type => ‘application/json‘), :72foo, :bar<?>;
用它發送請求, 可以像這樣:
jpost ‘http://localhost‘, JSON, %headers;
這是 jpost 請求, 會自動擷取 JSON 格式的 傳回值, 如果要擷取一般格式的響應請求, 可以用它的 POST 方法。
WWW 模組在如下地址可找到:
https://github.com/zoffixznet/perl6-WWW
我們可以看下它的 POST 源碼, 其實也是用了 HTTP::Request進行了封裝而已:
perl6 HTTP::UserAgent (3) JSON