Reputation: 41
I am very new to Perl and badly needing for help. I have a file.txt where I want to post its content to a webservice url.
This is the sample of my file.txt content.
Name: name1 Address: address1 Name: name2 Address: address2 Name: name3 Address: address3
And here it my post.pl (referencing from this site: http://xmodulo.com/how-to-send-http-get-or-post-request-in-perl.html)
#!/usr/bin/perl
use warnings;
use strict;
use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
my $url = "https://domain/post.php";
# set custom HTTP request header fields
my $req = HTTP::Request->new(POST => $url);
$req->content_type('application/json');
# add POST data to HTTP request body
my $post_data = '{"name":"myName", "address":"myAddress"}'; // I want to post here the content of file.txt
$req->content($post_data);
print $req->as_string;
my $resp = $ua->request($req);
if ($resp->is_success) {
my $message = $resp->decoded_content;
print "\nReceived reply: $message\n";
}
else {
print "HTTP POST error code: ", $resp->code, "\n";
print "HTTP POST error message: ", $resp->message, "\n";
}
Using above file and script, how can I possible post the contents of the file. Thank you in advance.
Upvotes: 3
Views: 6249
Reputation: 69244
You can use the post()
method from LWP::UserAgent to make this much simpler. Underneath, it uses the POST()
method from HTTP::Request::Common, so you can look there for more details about how it handles file uploads.
#!/usr/bin/perl
use warnings;
use strict;
use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
my $url = 'https://domain/post.php';
# The name of the file input field on the HTML form/
# You'll need to change this to whatever the correct name is.
my $file_input = 'file-input';
# Path to the local file that you want to upload
my $file_path = '/path/to/some/file';
my $req = $ua->post($url,
Content_Type => 'form-data',
Content => [
$file_input => [ $file_path ],
],
);
You don't even need to open the file yourself - HTTP::Request::Common does that for you.
Upvotes: 3
Reputation: 1173
OK, firstly, I'd like to say that the format your file.txt is in, is not a very intuitive format, because it's not in any standardized format, so we can't just invoke generic libs that do CSV or JSON parsing. Anyways, what you essentially need is to build a parsing function in between.
sub parse_file {
my ($filename) = @_;
open(FILE, $filename) or die sprintf ("Could not open '%s' (%s)", $filename, $!));
my $string = '';
my @args;
foreach my $line (<FILE>) {
chomp($line);
# Assumes that every record is separated by a blank line.
if ($line) {
my ($keyname, $value) = split(':', $line);
# Remove empty spaces left and right
$keyname =~ s/^\s+|\s+$//g;
$value =~ s/^\s+|\s+$//g;
$string = ($string)
? $string.', '.sprintf('"%s":"%s"', $keyname, $value);
: sprintf('"%s":"%s"', $keyname, $value);
}
else {
# When we have a blank line, store the string we have concatenated.
push (@args, sprintf("{%s}", $string);
$string = ''; # Reset the string for the next record
}
}
close(FILE) or die sprintf ("Could not close '%s' (%s)", $filename, $!));
return (wantarray) ? @args : \@args;
}
From the arguments that are returned from this function, you can then go
my @post_args = parse_file($path_to_your_file);
foreach my $post_arguments (@post_args) {
# Call your HTTP request to set post_arguments and post the form
}
Upvotes: 0
Reputation: 7723
Read content from file like below.
use strict;
use warnings;
use utf8;
open my $fh, '<', '/path/to/file.json' or die "failed to open: $!";
my $content = do { local $/; <$fh> };
close $fh;
Or
use File::Slurp;
my $content = read_file('/path/to/file.json');
Upvotes: 1