2014-12-13 26 views
1
#!/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提交HTTP POST請求,並提供XML文件內容作爲正文

我想使用LWP::UserAgent提交發布請求,我想給出一個XML文件的位置作爲正文。我收到無效的請求正文錯誤。請求正文無效

+0

請發表你的程序的文本,而不是圖像,使我們可以複製/粘貼它。你已經在你的[上一個問題]之前告訴過這個(http://stackoverflow.com/questions/27456928) – Borodin 2014-12-13 15:22:49

+0

好吧,現在請檢查。如果我傳遞內容,而不是傳遞文件,那麼它就可以工作。但我想通過XML文件 – 2014-12-13 15:39:22

回答

1

我不明白是什麼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; 
+0

感謝borodin。它的工作..! – 2014-12-14 05:46:58

相關問題