Chapter 4. URLs

现在你已经看到了LWP 模型的HTTP 请求和响应, 一个URL 会告诉你如何得到一些东西:

使用这个主机请求HTTP,”“连接通过FTP主机和检索此文件,”或“发送邮件到这个地址。”

在网址中的巨大变化即是祝福也是诅咒, 一方面,你可以把网址语法延伸到几乎任何类型的网络资源。

然而,这种非常灵活的手段试图解析任意URL正则表达式迅速陷入泥潭的特殊情况。

LWP 模块的套件提供了URL类 来管理URLs,本章提供了如何创建对象来代表URLs,从这些对象中提取信息,

转换决定和相对地址。

4.1. Parsing URLs 解析URLs

相比尝试拆开URL 用正则表达式, 这是很难做到用这种方式 在有很多类型的的URL,

你应该使用URL类, 当你创建一个对象代表一个URL的时候,它URL每个部分的属性(方案,用户名,主机名,端口,等等)。使方

法调用以获取和设置这些属性。

Example 4-1 创建一个URL 对象 表达一个复杂的URL, 然后调用方法来发现URL各个组成部分

use URI;
my $url = URI->new(‘http://user:pass@example.int:4345/hello.php?user=12‘);
print “Scheme: “, url>scheme(), ;printUserinfo:,url->userinfo( ), “ ”;
print “Hostname: “, url>host(), ;printPort:,url->port( ), “ ”;
print “Path: “, url>path(), ;printQuery:,url->query( ), “ ”

[root@dr-mysql01 test]# perl s1.pl
Scheme: http
Userinfo: user:pass
Hostname: example.int
Port: 4345
Path: /hello.php
Query: user=12

除了读取URL的部分,方法比如host() 可以同时噶边URL的一部分,使用熟悉的惯例,

object>method,object->method(newvalue) 改变一个属性的值

use URI;
my $uri = URI->new(“http://www.perl.com/I/like/pie.html“);
uri>host(testing.perl.com);printuri,” ”;
http://testing.perl.com/I/like/pie.html

4.1.1 构造函数

URL 类的对象 代表一个URL,(实际上,URL对象能表达一些类似的URL 字符串称为URN)

创建一个URL 对象,使用new() 构造

如果url 是一个真实的URL( 一个片段比如 staff/alicia.html),schema 决定了你计划的URL

(http,FTP等).但是在很多情况下,你可以 调用URL-new 只有当你知道你不会有一个相对的URL,

对于相对的URLs或者URLs 肯可能是相对的,使用URL->new_abs 方法,下面讨论下:

URL 模块带了引号,括号 并从新的URL空格。所以这些陈述都创造相同的URI对象:

$url = URI->new(‘http://www.oreilly.com/‘);
$url = URI->new(‘”http://www.oreilly.com/“’);
$url = URI->new(’ http://www.oreilly.com/‘);
$url = URI->new(‘http://www.oreilly.com/ ‘);

URI 自动转义任何字符 参照URL 标注(RFC 2396) ,不能出现在URL的字符,两者等价

$url = URI->new(‘http://www.oreilly.com/bad page’);
$url = URI->new(‘http://www.oreilly.com/bad%20page‘);

如果你已经有一个URL对象,clone()方法会产生具有相同属性的另一个URL对象:

copy=url->clone( );
Example 4-2 clones a URI object and changes an attribute.

Example 4-2. Cloning a URI
use URI;
my $url = URI->new(‘http://www.oreilly.com/catalog/‘);
dup=url->clone( );
url>path(/weblogs);printChangedpath:,url->path( ), “ ”;
print “Original path: “, $dup->path( ), “ ”;
When run, Example 4-2 prints:

Changed path: /weblogs

4.1.2 Output

对象一个URL 对象作为字符窜 ,你需要get URL:

$url = URI->new(‘http://www.example.int‘);
url>path(/search.cgi);printTheURLisnow:url ”;
The URL is now: http://www.example.int/search.cgi

你可以发现它是有用的 对URL进行标准化

$url->canonical( );

4.1.3. Comparison 比较

比较两个URL 使用 eq() 方法:

if ($url_one->eq(url_two)) { … }

比如:

use URI;
my $url_one = URI->new(‘http://www.example.int‘);
my $url_two = URI->new(‘http://www.example.int/search.cgi‘);
urlone>path(/search.cgi);if(url_one->eq($url_two)) {
print “The two URLs are equal. ”;
}
The two URLs are equal.

4.1.4. Components of a URL URL的组成

URL 类提供方法来访问每个部件,一些部件只能在某些schemes(比如: maito:URLs 不支持 userinfo,host,或者端口组件)

在除了显而易见的scheme(),userinfo(),port(),query()和fragment() 方法, 这是一些有用但不那么直观的。

原文地址:https://www.cnblogs.com/hzcya1995/p/13351526.html