tokuhirom's Blog

超適当な http client

use strict;
use warnings;
use 5.10.0;
use IO::Socket::INET;
use HTTP::Response::Parser qw/parse_http_response/;
use URI;
use YAML;

my $CRLF = "\015\012";

warn Dump(get('http://mixi.jp/'));

sub get {
    my ($url) = @_;

    my $uri = URI->new($url);
    my $sock = IO::Socket::INET->new(
        PeerHost => $uri->host,
        PeerPort => $uri->port || 80,
    ) or die "cannot open socket$!";
    print {$sock} sprintf("GET %s HTTP/1.0${CRLF}Host: %s${CRLF}${CRLF}", $uri->path || '/', $uri->host);

    my $ret;
    my $buf = do { local $/; <$sock> };

    my $res = HTTP::Response::Parser::parse($buf);
    if ($res) {
        return $res;
    } else {
        die "something wrong"
    }
}