urlopen method in Perl 6?

I have reduced the program to the bare minimum; you will still have to take care of headers and the OAuth query, but this works

use WWW;

sub MAIN( :$have-data = 0 ) {
    my $url='https://jsonplaceholder.typicode.com/posts/';
    my %args=%(form-data => "userId=1&id=2");
    my $data = "";

    if $have-data {
        $data = %args{'form-data'};
    } 

    my $res;
    if $data {
        $res = post $url, $data;
    } else {
        $res= get $url~'1';
    }
    say $res;
}

Baseline is that urlopen in Python does get or post depending on whether there is data or not. In this case, I use a simple if for that purpose, since WWW is quite barebones and does not support that. I am using also a mock REST interface, so I have actually to change the URL depending on the data, which is also dummy data. You can call the program either with no argument or with

perl6 urlopen.p6 --have-data=1

and the mock server will return... something. It would be great if you contributed a module with a (somewhat) higher level than WWW, or to WWW itself. Hope this solves (kinda) your problem.


use Cro::HTTP::Client;

my $resp;
my $data = "";

if (%headers{'content-type'} // '') eq self.form_urlencoded {
    $data = oauth_query(%args);
} elsif (%headers{'content-type'} // '').contains('form-data') { # multipart/form-data
    $data = %args{'form-data'};
} else {
    $data = "";
}

my $client = Cro::HTTP::Client.new(headers =>  |%headers);

if $data {
    $resp = await $client.post: $url, body => |%args;
} else {
    $resp = await $client.get: $url;
}

return $resp;

Tags:

Raku