我尝试连接到https URL以存储对字符串的响应。将套接字响应存储在Perl中的字符串中
use strict;
use warnings;
use IO::Socket::SSL;
my $socket = IO::Socket::SSL->new(
PeerHost => "google.com",
PeerPort => "https"
) or die "Error: $!";
print $socket "GET/HTTP/1.0\r\n\r\n";
my $content = <$socket>;
print $content;
print "length: ";
print length($content);
print "\n";
close $socket;
的输出是仅在HTTP响应的第一行:
HTTP/1.0 302 Found
length: 20
当我改变脚本,并打印与“打印”的响应,输出是完整repsonse:
use strict;
use warnings;
use IO::Socket::SSL;
my $socket = IO::Socket::SSL->new(
PeerHost => "google.com",
PeerPort => "https"
) or die "Error: $!";
print $socket "GET/HTTP/1.0\r\n\r\n";
print <$socket>;
close $socket;
输出:
HTTP/1.0 302 Found
Cache-Control: private
Content-Type: text/html; charset=UTF-8
Location: https://www.google.de/?gfe_rd=cr&ei=XAroVeuYDMWo8wfioYKQBw
Content-Length: 259
Date: Thu, 03 Sep 2015 08:52:44 GMT
Server: GFE/2.0
Alternate-Protocol: 443:quic,p=1
Alt-Svc: quic=":443"; p="1"; ma=604800
<HTML>...</HTML>
我不明白为什么我无法将套接字响应存储到字符串中。
我使用Perl v5.14.2
<$socket>将采取不同的行为取决于上下文。对标量上下文中的句柄的调用将返回句柄中的下一行。对列表上下文中的句柄的调用将每行返回给您。打印是列表上下文,其中分配给标量是上下文。 –
试试'my $ content = join('',<$socket>);'。 Join将在列表上下文中读取'<$socket>',然后将每一行连接在一起并返回一个字符串,然后可以将它分配给您的标量变量。 –