Solution to the POST file with REST
First of all I want to say thank you all for the effort and time and
I finally found the only solution that worked for me is a combination of LWP::UserAgent and HTTP::Request::Common.
Sample of working code bellow (for future reference):
#!/usr/bin/perl
use JSON;
use strict;
use warnings;
use MIME::Base64;
use Data::Dumper;
use feature 'say';
use LWP::UserAgent ();
use HTTP::Request::Common;
my $ua = LWP::UserAgent->new;
$ua->timeout(10);
$ua->env_proxy;
my $url = "http://127.0.0.1:8000/upload/";
my $file = "test.txt";
$HTTP::Request::Common::DYNAMIC_FILE_UPLOAD = 1;
my $req = POST(
$url,
Authorization => 'Basic ' . encode_base64('user' . ':' . 'password
+'),
Content_Type => 'multipart/form-data',
Content => [ file => [$file] ],
);
my $res = $ua->request($req); #do it
say $res->status_line;
my $response = $ua->get('http://127.0.0.1:8000/snippets/1/');
if ($response->is_success) {
print Dumper decode_json($response->decoded_content); # or whatev
+er
}
else {
die $response->status_line;
}
__END__
$ perl test.pl
201 Created
$VAR1 = {
'highlight' => 'http://127.0.0.1:8000/snippets/1/highlight/'
+,
'url' => 'http://127.0.0.1:8000/snippets/1/',
'id' => 1,
'owner' => 'user',
'code' => 'Test POST file Perl',
'language' => 'perl',
'title' => 'Default Title',
'style' => 'emacs',
'linenos' => bless( do{\(my $o = 0)}, 'JSON::PP::Boolean' )
};
I know that most people will say why not use the LWP::UserAgent::credentials, I tried to use it but it did not worked for me so I used the old traditional manual adding credentials to header. Works like a charm. :)
Seeking for Perl wisdom...on the process of learning...not there...yet!
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|