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请求,

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

  1. perl mysql dbi 安装_Perl中DBI、DBD::mysql模块的安装

    Perl中DBI.DBD::mysql模块的安装 Perl中DBI.DBD::mysql模块的安装 使用的软件版本 DBI-1.604.tar.gz DBD-mysql-4.006.tar.gz 建议 ...

  2. LWP::UserAgent的用法

    LWP::UserAgent是一个模拟用户浏览器的类,在使用的时候需要遵守以下几步: 1.引入模块 2.创建一个LWP::UserAgent的对象 3.设置这个对象的相关参数 4.创建HTTP::Re ...

  3. [Perl系列—] 2. Perl 中的引用用法

    Perl 中的引用,为什么要使用引用? 对于熟悉C语言的开发者来说, 指针这个概念一定不陌生. Perl 的引用就是指针,可以指向变量.数组.哈希表甚至子程序. Perl5中的两种Perl引用类型为硬 ...

  4. perl中last的用法

    在C语言中,如果想要退出一个循环,我们可以使用break.在perl中,没有beak这个关键字,但是perl却也提供了另外一个关键字,让程序从循环中跳出,那就是last.现在我们就看一下last的使用 ...

  5. python argparse模块详解_python中argparse模块用法实例详解

    本文实例讲述了python中argparse模块用法.分享给大家供大家参考.具体分析如下: 平常在写命令行工具的时候,经常会带参数,所以用python中的argparse来实现. # -*- codi ...

  6. ubuntu18.0.4 不能下载 libgd2-dev(ubuntu 20.04 安装perl 中GD 模块失败的解决办法)

    ubuntu18.0.4 不能下载 libgd2-dev 一.错误信息: Unable to locate package libgd2-dev 二.原因 没有对应源 到 https://packag ...

  7. python中mysqldb模块_python中MySQLdb模块用法实例

    本文实例讲述了python中MySQLdb模块用法.分享给大家供大家参考.具体用法分析如下: MySQLdb其实有点像php或asp中连接数据库的一个模式了,只是MySQLdb是针对mysql连接了接 ...

  8. python pygame模块_python中pygame模块用法实例

    本文实例讲述了python中pygame模块用法,分享给大家供大家参考.具体方法如下: import pygame, sys from pygame.locals import * #set up p ...

  9. 在 Perl 中使用 Getopt::Long 模块来接收用户命令行参数

    我们在linux常常用到一个程序需要加入参数,现在了解一下 perl 中的有关控制参数的模块 Getopt::Long ,比直接使用 @ARGV 的数组强大多了.我想大家知道在 Linux 中有的参数 ...

最新文章

  1. SAP WM高阶之下架策略M(Small Large Quantity)
  2. 035 函数和代码复用小结
  3. maven 和eclipse插件
  4. mysql开启慢查询
  5. Python之IO编程——文件读写、StringIO/BytesIO、操作文件和目录、序列化
  6. Java进阶之光!mysql安装包安装教程
  7. java+包装类,装箱和拆箱_Java包装类,装箱和拆箱详解
  8. 【script】python自定义时间格式的几种情况
  9. 中概股信任危机?美证监会主席直言不要购买中概股股票
  10. 开发者生态与双引擎:华为的雄心壮志!
  11. html左侧树形图,Qunee for HTML5 - 中文 : 树形布局
  12. Verge3D 2.12 for 3ds Max发布
  13. 汽车电子设计之SBC芯片简单认识
  14. 记录一次idea因为虚拟内存不足而闪退的经历
  15. 记录一下Unity学习中的一些奇异事件
  16. Syclover-Web题解
  17. 因一个 Bug,谷歌、GitHub、亚马逊等网站全球大范围宕机!
  18. AForge.net 使用之录像拍照功能实现
  19. Linux_基本指令
  20. 计算语言学之汉语分词

热门文章

  1. AlphaGo 超快棋遍虐人类高手(职业棋手讲解及大量网友评论)
  2. shiro+jwt登录认证anon配置无效
  3. Vim编辑器的基本使用(二)末行模式中的命令
  4. Python爬虫系列:腾讯课堂Scrapy爬虫
  5. mui赋值_mui input用法
  6. 《Qt5 Cadaques》学习笔记(六):QT QUICK Controls 2
  7. Python 进程 自定义进程子类 继承
  8. Spring MVC集成Swagger2.0
  9. 每个程序员必须掌握的常用英语词汇
  10. android hdmi拔插广播,Android_8.1插拔hdmi后,音量会变到最大