Perl 中关于 LWP::UserAgent等模块用法

LWP::UserAgent

用法:
 require LWP::UserAgent;
 
 my $ua = LWP::UserAgent->new;
 $ua->timeout(10);
 $ua->env_proxy;
 
 my $response = $ua->get('http://search.cpan.org/');
 
 if ($response->is_success) {
     print $response->content;  # or whatever
 }
 else {
     die $response->status_line;
 }

LWP::UserAgent是一个模拟用户浏览器的类,在使用的时候得首先创建一个LWP::UserAgent的对象,然后再设置这个对象的相关参数,它然后再创建HTTP::Request实例,并发送请求,并返回HTTP::Response对象。
1.创建LWP::UserAgent对象
$ua = LWP::UserAgent->new( %options ) 
options的键值如下:
   KEY                     DEFAULT
   -----------             --------------------
   agent                   "libwww-perl/#.##"
   from                    undef
   conn_cache              undef
   cookie_jar              undef
   default_headers         HTTP::Headers->new
   max_size                undef
   max_redirect            7
   parse_head              1
   protocols_allowed       undef
   protocols_forbidden     undef
   requests_redirectable   ['GET', 'HEAD']
   timeout                 180
另外,如果env_proxy的值设为真,那么代理设置将有效(参见env_proxy());如果keep_alive为真,那么LWP::ConnCache将建立(参见conn_cache())。

$ua->clone  返回LWP::UserAgent对象的一个拷贝

2.LWP::UserAgent对象属性
2.1 $ua->agent 
$ua->agent( $product_id ) 
用来返回或者设置用户的agent,用来在header中告诉服务器你用的是什么"浏览器",设置文件头的User-Agent。缺省值是 _agent()返回的字符串。如果$product_id以空格结尾,那么_agent()的返回值将加到$product_id后面。user-agent必须是以/分割的浏览器名+版本号,如:
  $ua->agent('Checkbot/0.4 ' . $ua->_agent);
  $ua->agent('Checkbot/0.4 ');    # same as above
  $ua->agent('Mozilla/5.0');
  $ua->agent("");                 # don't identify

$ua->_agent返回缺省的agent值,形如"libwww-perl/#.##"

2.2 $ua->from 
$ua->from( $email_address ) 
返回或者设置发起请求的人的邮件地址,设置文件头的from。如:
$ua->from('gaas@cpan.org');
默认设置是不发送from键值

2.3 $ua->cookie_jar 
$ua->cookie_jar( $cookie_jar_obj ) 
返回或者设置cookie,在运行过程中必须执行两个方法,extract_cookies($request) 和 add_cookie_header($response)。在运行的过程中实际用到了HTTP::Cookies模块。如:
  $ua->cookie_jar({ file => "$ENV{HOME}/.cookies.txt" });
等价于
  require HTTP::Cookies;
  $ua->cookie_jar(HTTP::Cookies->new(file => "$ENV{HOME}/.cookies.txt"));

2.4 $ua->default_headers 
$ua->default_headers( $headers_obj ) 
设置或返回每一次请求的headers值,缺省是一个空的HTTP::Headers 对象
  $ua->default_headers->push_header('Accept-Language' => "no, en");
$ua->default_header( $field ) 
$ua->default_header( $field => $value )

如:
my %headers=('Accept'=>'image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/QVOD, */*',
'Accept-Language'=>'zh-cn',
'User-Agent'=>'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727)',
'Accept-Charset' => 'iso-8859-1,*,utf-8');
my $response = $browser->get($url,%headers);

2.5 $ua->conn_cache 
$ua->conn_cache( $cache_obj ) 
设置或返回LWP::ConnCache 对象

2.6 $ua->credentials( $netloc, $realm, $uname, $pass ) 
设置访问一个域的时候的用户名和密码

2.7 $ua->max_size 
$ua->max_size( $bytes ) 
设置或返回响应内容的大小。缺省是undef,意思是不限制。

2.8 $ua->max_redirect 
$ua->max_redirect( $n ) 
设置或返回被请求页面所跳转的最大次数。默认为7

2.9 $ua->parse_head 
$ua->parse_head( $boolean ) 
设置或返回是否我们初始化响应的HTML的<head></head>标签内容。默认是TRUE,不要将这个值关闭,除非你知道你在做什么。

2.10 $ua->protocols_allowed 
$ua->protocols_allowed( \@protocols ) 
设置或返回发起请求的方法,方法名对大小写敏感。例如$ua->protocols_allowed( [ 'http', 'https'] ); 表明该用户只允许这两种协议。如果用其他的协议访问URL(like "ftp://...")将会导致500错误
删除这个设置的方法: $ua->protocols_allowed(undef)

2.11 $ua->protocols_forbidden 
$ua->protocols_forbidden( \@protocols ) 
与2.10类似

2.12 $ua->requests_redirectable 
$ua->requests_redirectable( \@requests ) 
push @{ $ua->requests_redirectable }, 'POST';告诉LWP在POST请求发送后如果发生重新定向就自动跟随

2.13 $ua->timeout 
$ua->timeout( $secs ) 
设置缓冲时间,默认180s

3.代理属性
$ua->proxy(\@schemes, $proxy_url) 
$ua->proxy($scheme, $proxy_url) 
如 
 $ua->proxy(['http', 'ftp'], 'http://proxy.sn.no:8001/');
 $ua->proxy('gopher', 'http://proxy.sn.no:8001/');
指明通过制定的代理服务器,按照指定的协议方法访问。

$ua->env_proxy从*_proxy 环境变量获取代理设置,如:
  gopher_proxy=http://proxy.my.place/
  wais_proxy=http://proxy.my.place/
  no_proxy="localhost,my.domain"
  export gopher_proxy wais_proxy no_proxy

4.请求方法
4.1 $ua->get( $url ) 
$ua->get( $url , $field_name => $value, ... ) 
    :content_file   => $filename     将返回的文件按照$filename保存下来,对大文件应该如此,不然保存在内存中。
    :content_cb     => \&callback    callback执行的函数,这个选项与:content_file只能设置其一。
    :read_size_hint => $bytes
如:$response=$ua->get('http://search.cpan.org/',':content_file'=>'/tmp/sco.html')

4.2 $ua->head( $url ) 
$ua->head( $url , $field_name => $value, ... )

4.3 $ua->post( $url, \%form ) 
$ua->post( $url, \@form ) 
$ua->post( $url, \%form, $field_name => $value, ... ) 
如:$response = $browser->post( $url,[formkey1 => value1,formkey2 => value2,...],headerkey1 => value1,headerkey2 => value2, );
可以用来提交搜索等等,总之就是构造网址。

4.4 $ua->mirror( $url, $filename ) 获取$url指定的文件,并按照$filename保存下来。

4.5 $ua->request( $request ) 
$ua->request( $request, $content_file ) 
$ua->request( $request, $content_cb ) 
$ua->request( $request, $content_cb, $read_size_hint )

4.6 $ua->simple_request( $request ) 
$ua->simple_request( $request, $content_file ) 
$ua->simple_request( $request, $content_cb ) 
$ua->simple_request( $request, $content_cb, $read_size_hint )

4.7 $ua->is_protocol_supported( $scheme )




perl http模块总结

  perl发送http请求主要有 LWP,UserAgent, HTTP这些模块及其子模块组成

  1.发送简单的http请求

  只需要使用LWP::Simple模块即可

  use LWP::Simple;

  $content = get(url); #返回得到的内容

  getstore(url, filename);#将目标url的内容保存到filename中

  head($url); 返回5个响应头($content_type, $document_length, $modified_time, $expires, $server)

  这个模块的方法只能做一些基本的http请求操作,比如只能发送get请求,获取不到响应的详细信息

  2.发送通用的http请求

  这里用到3个主要的类

  LWP::UserAgent, HTTP::Request, HTTP::Response,

  需要注意的是 后面2个类继承HTTP::Headers和 HTTP::Message, HTTP::Headers 提供了添加请求头,获取响应头的方法。 HTTP::Message提供了content方法,对于request对象,如果request是post请求,则该方法会设置http的请求内容; 对于response对象该方法会返回http响应的内容

  标准的请求过程

  $response = $ua->request($request);

  在执行此方法之前可以对request对象进行设置, 方法执行完后

  可以从response对象中获取内容,响应头等

  UserAgent可以设置一些s全局选项, 比如timeout,max_redirect

  下面是一个完整的例子

  use LWP::UserAgent;

  use HTTP::Request;

  use HTTP::Response;

  $ua = LWP::UserAgent->new(timeout=>180);

  $request = HTTP::Request->new('POST'=$amp;>quot;$");

  $request->content('age=18');#post 请求参数

  $request->header('Accept-Language', 'zh-CN,zh;q=0.8');

  $response = $ua->request($request);

  print $response->content();

  print $response->status_line();

  print $response->header('Content-Type');

  总结:

  通过使用 LWP::UserAgent, HTTP::Request, HTTP::Response, 这三个类可以满足发起大多数http请求,


  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值