[英]Submit HTTP POST request using LWP::UserAgent giving XML file contents as body
#!/usr/bin/perl -w
use strict;
use FileHandle;
use LWP::UserAgent;
use HTTP::Request;
sub printFile($) {
my $fileHandle = $_[0];
while (<$fileHandle>) {
my $line = $_;
chomp($line);
print "$line\n";
}
}
my $message = new FileHandle;
open $message, '<', 'Request.xml' or die "Could not open file\n";
printFile($message);
my $url = qq{https://host:8444};
my $ua = new LWP::UserAgent(ssl_opts => { verify_hostname => 0 });
$ua->proxy('http', 'proxy:8080');
$ua->no_proxy('localhost');
my $req = new HTTP::Request(POST => $url);
$req->header('Host' => "host:8444");
$req->content_type("application/xml; charset=utf-8");
$req->content($message);
$req->authorization_basic('TransportUser', 'TransportUser');
my $response = $ua->request($req);
my $content = $response->decoded_content();
print $content;
I am getting the following error. 我收到以下错误。
I want to submit post request using LWP::UserAgent
and I want to give the location of an XML file as the body. 我想使用LWP::UserAgent
提交发布请求,并且想给出XML文件的位置作为正文。 I am getting invalid request body error. 我收到无效的请求正文错误。 Request Body is invalid 请求正文无效
I don't understand what printFile
is for, but you are passing file handle $message
as the message body, not the contents of the file. 我不了解printFile
的用途,但是您正在将文件句柄 $message
作为消息正文而不是文件内容进行传递。
Please take note of the following 请注意以下几点
Always use warnings
instead of the -w
comment line option 始终 use warnings
而不是-w
注释行选项
Never use subroutine prototypes. 切勿使用子例程原型。 sub printFile($)
should be just sub printFile
sub printFile($)
应该只是sub printFile
There is no need to use FileHandle
to work with files 无需use FileHandle
处理文件
The reason for a file open
failure is in $!
之所以一个文件open
失败是$!
. 。 You should always include it in the die
string 您应该始终将其包含在die
字符串中
Never use the indirect object notation. 切勿使用间接对象符号。 new LWP::UserAgent
should be LWP::UserAgent->new
new LWP::UserAgent
应该是LWP::UserAgent->new
This version of your code may work a little better, but I have no way of testing it 此版本的代码可能会更好一些,但我无法对其进行测试
#!/usr/bin/perl
use strict;
use warnings;
use LWP;
my $message = do {
open my $fh, '<', 'Request.xml' or die "Could not open file: $!";
local $/;
<$fh>;
};
my $url = 'https://host:8444';
my $ua = LWP::UserAgent->new(ssl_opts => { verify_hostname => 0 });
$ua->proxy(qw/ http proxy:8080 /);
$ua->no_proxy('localhost');
my $req = HTTP::Request->new(POST => $url);
$req->header(Host => 'host:8444');
$req->content_type('application/xml; charset=utf-8');
$req->content($message);
$req->authorization_basic('TransportUser', 'TransportUser');
my $response = $ua->request($req);
my $content = $response->decoded_content;
print $content;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.