编写一个小而灵活的HTTP客户端

时间:2010-11-18 23:10:58

标签: python ruby perl http

我正在寻找人们如何编写一个快速(小)但灵活的HTTP客户端。快速我的意思是代码不多,(我将由你来决定这意味着什么),并且最好使用内置语言函数而不是下载或自定义库,这样套接字编程的基本知识应该是足以理解代码的工作原理。灵活的我的意思是你应该能够轻松地操纵传入的数据。我自己的这种类型的版本将是

#!/usr/bin/perl
use Socket;
use HTML::Parse;

socket(SOCKH, PF_INET, SOCK_STREAM, getprotobyname('tcp')) || die $!;
connect(SOCKH,sockaddr_in(80,inet_aton('www.example.com'))) || die $!;

$old_fh = select(SOCKH);
$|=1;
select($old_fh);

print SOCKH "GET / HTTP/1.0\n\n";

while (<SOCKH>) {
    $response .= $_;
}

print parse_html($response)->format;

close(<SOCKH>);

这只是一个快速的客户端,我很快就会为HTTP / 1.1进行编辑,或者如果您有关于如何更好地完成合规性的建议请分享!

编辑:我的代码更新,使用LWP作为Sinan Unur建议:

#!/usr/bin/perl
use LWP::Simple;
use HTML::Parse;

$data = parse_html( get( 'www.example.com' ) )->format;
foreach $line ( $data ) {
    print $line; // or any other line-based operation
}

7 个答案:

答案 0 :(得分:9)

Perl有LWP。我建议你使用它。

答案 1 :(得分:2)

与@ Santa的例子类似,仅在Ruby中:

require 'open-uri'
print open('http://www.example.com').read

如果要解析内容,Ruby的Nokogiri gem非常棒。它建立在libXML之上。

许多其他HTTP客户端gem可用,包括HTTPartyTyphoeus。 HTTParty使得向类添加REST功能以及解析JSON和XML的能力变得微不足道。 Typhoeus可以很容易地同时为并行获取/头/ whatevers写入多个请求。

答案 2 :(得分:2)

Python有“包含电池”

您不需要在套接字级别工作(尽管可以)。 Python在其标准库中构建了几个更高级别的Web / http库。

例如,在Python 2中,您可以使用urllib2

import urllib2

response = urllib2.urlopen('http://www.example.com/')
html = response.read()

还可以查看httplib,以获得稍低级别的访问权限:

>>> import httplib
>>> conn = httplib.HTTPConnection("www.python.org")
>>> conn.request("GET", "/index.html")
>>> r1 = conn.getresponse()
>>> print r1.status, r1.reason
200 OK
>>> data1 = r1.read()
>>> conn.request("GET", "/parrot.spam")
>>> r2 = conn.getresponse()
>>> print r2.status, r2.reason
404 Not Found
>>> data2 = r2.read()
>>> conn.close()

答案 3 :(得分:1)

#!/usr/bin/env python

import urllib

f = urllib.urlopen('http://www.example.com')
print f.read()
f.close()

答案 4 :(得分:1)

在您开始需要做任何繁重的事情之前,大量示例似乎微不足道,例如在两个方向上传输千兆字节的数据。我最喜欢的是ruby的net/http,它是每个ruby安装的一部分。

以下是流式传输数据的示例,并在您完成更多请求后保持连接处于打开状态。

require 'net/http'

http = Net::HTTP.new('my.server.org')
http.start

req = Net::HTTP::Post.new('/path/to/huge/file')
req.basic_auth('user', 'pass')
req.content_length = File.size 'huge_input_file.txt'
req.body_stream = File.open('huge_input_file.txt', 'rb')

http.request(req){|res|
  File.open('huge_output_file.txt', 'wb'){|f|
    res.read_body {|chunk| f.write chunk}
  }
}

Perl没有任何内置功能。 Net::HTTPLWP::UserAgent不属于perl核心。前段时间我需要一个perl http客户端,其功能类似于上面的ruby示例,而不依赖于CPAN中的任何内容。仅花费不到200行,仅使用IO::Socket::INETsyswrite / sysread(这消除了很多低层套接字废话),并MIME::Base64进行身份验证。

答案 5 :(得分:1)

我认为你实际上并不想编写自己的http客户端,而是使用http获取内容的脚本?

其他人提及HTTP::LiteLWP::Simple ..

以下是使用文档中的Mojo::Client的示例。

# Quick JSON request
my $trends = 'http://search.twitter.com/trends.json';
print $client->get($trends)->res->json->{trends}->[0]->{name};

# Extract data from HTML and XML resources
print $client->get('mojolicious.org')->res->dom->at('title')->text;

# Scrape the latest headlines from a news site
my $news = 'http://digg.com';
$client->max_redirects(3);
$client->get($news)->res->dom('h3 > a.story-title')->each(sub {
    print shift->text . "\n";
});

酷,但不是最成熟的模块..

答案 6 :(得分:0)

我看不出你对这个问题的任何答案会得到什么好处,但我会屈服于同伴的压力。既然你似乎不打扰使用哪种语言......

如果你想以有趣的方式操纵它:

<?php
$d=new DOMDocument();
$d->loadHTMLFile('http://www.example.com/');
...

但是要返回一页:

<?php
print file_get_contents('http://www.example.com/');
相关问题