http-useragent
http-useragent copied to clipboard
It doesn't seem possible to POST application/json data
I'm trying to create a POST request like:
POST /foo HTTP/1.1
Content-Type: application/json
Host: example.com
{"foo":1, "bar": 2}
As far as I can figure out, this is not currently possible.
If I set the Content-Type
header of the request to 'application/json'
, add-form-data
seems to do nothing at all.
Sure it's possible, it's just not immediately obvious from the documentation :)
The easiest way is to create the HTTP::Request object with the POST
helper in HTTP::Request::Common
:
use HTTP::Request::Common;
use HTTP::UserAgent;
my $r = POST('http://example.com/foo', content => '{"foo":1, "bar": 2}', Content-Type => "application/json");
say $r.Str;
my $au = HTTP::UserAgent.new;
say $au.request($r).Str;
Which will give you a request like:
POST /foo HTTP/1.1
Host: example.com
Content-Type: application/json
Content-Length: 19
{"foo":1, "bar": 2}
In the general case if you want to create the HTTP::Request
by hand, you would want to use add-content
rather than add-form-data
:
use HTTP::Request;
my $r = HTTP::Request.new(POST => 'http://example.com/foo');
$r.header.field(Content-Type => 'application/json');
$r.add-content: '{"foo":1, "bar": 2}';
say $r.Str;
I would however agree if you were to say that this might not be particularly well documented.

This is really a shit. The data is forcely encoded as application/x-www-form-urlencoded
.