繁体   English   中英

使用LWP :: UserAgent提交HTTP POST请求,并将XML文件内容作为正文

[英]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;

我收到以下错误。

我想使用LWP::UserAgent提交发布请求,并且想给出XML文件的位置作为正文。 我收到无效的请求正文错误。 请求正文无效

我不了解printFile的用途,但是您正在将文件句柄 $message作为消息正文而不是文件内容进行传递。

请注意以下几点

  • 始终 use warnings而不是-w注释行选项

  • 切勿使用子例程原型。 sub printFile($)应该只是sub printFile

  • 无需use FileHandle处理文件

  • 之所以一个文件open失败是$! 您应该始终将其包含在die字符串中

  • 切勿使用间接对象符号。 new LWP::UserAgent应该是LWP::UserAgent->new

此版本的代码可能会更好一些,但我无法对其进行测试

#!/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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM