如何使用Perl脚本发布文件的内容

时间:2014-12-16 01:47:19

标签: perl post

我是Perl的新手,非常需要帮助。 我有一个file.txt,我想将其内容发布到webservice网址。

这是我的file.txt内容的示例。

Name: name1
Address: address1

Name: name2
Address: address2

Name: name3
Address: address3

这是我的post.pl(引自本网站: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";
   }

使用上面的文件和脚本,我怎样才能发布文件的内容。 提前谢谢。

3 个答案:

答案 0 :(得分:2)

您可以使用LWP::UserAgent中的post()方法来简化这一过程。在下面,它使用HTTP::Request::Common中的POST()方法,因此您可以查看有关如何处理文件上传的更多详细信息。

#!/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 ],
  ],
);

你甚至不需要自己打开文件 - HTTP :: Request :: Common为你做这件事。

答案 1 :(得分:1)

从下面的文件中读取内容。

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;

或者

use File::Slurp;
my $content = read_file('/path/to/file.json');

答案 2 :(得分:0)

好的,首先,我想说你的file.txt所在的格式不是一个非常直观的格式,因为它不是任何标准格式,所以我们不能只调用执行CSV的通用库或JSON解析。无论如何,你最需要的是在两者之间建立一个解析函数。

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;
}

从这个函数返回的参数中,你可以去

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
}