gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 02:22:09 26 4
gpt4 key购买 nike

我是 Perl 的新手,急需帮助。我有一个 file.txt,我想将其内容发布到网络服务 url。

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

Name: name1Address: address1Name: name2Address: address2Name: name3Address: 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";
}

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

最佳答案

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

#!/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 会为您完成。

关于perl - 如何使用 Perl 脚本发布文件的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27496256/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com