sergot / http-useragent

Web user agent class for Perl 6.
MIT License
36 stars 39 forks source link

It doesn't seem possible to POST application/json data #214

Open mscha opened 6 years ago

mscha commented 6 years ago

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.

jonathanstowe commented 6 years ago

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.

Antisunny commented 5 years ago
image

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