之前想过直接获取url通过拼接字符串的方式实现,但是这种只是暂时的,后续地址如果有变化或参数很多,去岂不是要拼接很长,由于这些等等原因,所以找了一些方法实现
java.net.URI
URI全称是Uniform Resource Identifier,也就是统一资源标识符,它是一种采用特定的语法标识一个资源的字符串表示。URI所标识的资源可能是服务器上的一个文件,也可能是一个邮件地址、图书、主机名等
URI是标识一个资源的字符串
URI的语法
URI的语法构成是:一个模式和一个模式特定部分。表示形式如下:
模式:模式特定部分
scheme:scheme specific part
模式特定部分的表示形式取决于所使用的模式。URI当前的常用模式包括:
- data:链接中直接包含经过BASE64编码的数据。
- file:本地磁盘上的文件。
- ftp:FTP服务器。
- http:使用超文本传输协议。
- mailto:电子邮件的地址。
- magnet:可以通过对等网络(端对端P2P,如BitTorrent)下载的资源。
- telnet:基于Telnet的服务的连接。
- urn:统一资源名(Uniform Resource Name)。
URI中的模式特定部分没有固定的语法,不过,很多时候都是采用一种层次结构形式,如:
//授权机构/路径?查询参数//authority/path?query
URI的模式的组成部分可以是小写字母
、数字
、加号
、点(.)
和连号(-)
。
典型的URI的其他三个部分:模式特定部分,也就是授权机构;路径;查询参数
- 分别由ASCII字母组成(也就是字母A-Z、a-z和数字0-9),此外,还可以使用标点符号-、_、.、!和~,
- 定界符(如/、?、&和=)有其预定义的用途。
- 所有的其他字符,包括ASCII中拉丁字母,都需要使用百分号(%)转义,转义后的格式是:%+字符按照UTF-8编码再转成16进制的字符串表示。
- 注意一点,如果前面提到的定界符没有作为定界符使用,也需要进行转义。
- 举个简单的例子,如URI中存在中文字符"木",木字的UTF-8编码为0xE6 0x9C 0xA8,那么它在URI中应该转义为%E6%9C%A8。Jdk中的URLEncoder或者apache-codec中的相关类库提供URI(URL)编码的功能
URI中还可以携带用户的口令,因为会有安全漏洞,所以并不常见
构造URI实例
private URI() { } // Used internally// 根据提供的一个uri字符串构造一个URI对象
public URI(String str) throws URISyntaxException {new Parser(str).parse(false);
}//通过 模式、用户信息、服务器地址、端口、文件路径、查询条件、片段标识构造URI
public URI(String scheme,String userInfo, String host, int port,String path, String query, String fragment)throws URISyntaxException
{String s = toString(scheme, null,null, userInfo, host, port,path, query, fragment);checkPath(s, scheme, path);new Parser(s).parse(true);
}
// 通过 模式、授权机构、文件路径、查询条件、片段标识构造URI
public URI(String scheme,String authority,String path, String query, String fragment)throws URISyntaxException
{String s = toString(scheme, null,authority, null, null, -1,path, query, fragment);checkPath(s, scheme, path);new Parser(s).parse(false);
}// 通过 模式、服务器地址、文件路径、片段标识构造URI。public URI(String scheme, String host, String path, String fragment)throws URISyntaxException{this(scheme, null, host, -1, path, null, fragment);}//通过 模式、模式特定部分和片段标识创建URI。
public URI(String scheme, String ssp, String fragment)throws URISyntaxException
{new Parser(toString(scheme, ssp,null, null, null, -1,null, null, fragment)).parse(false);
}/**
* Constructs a simple URI consisting of only a scheme and a pre-validated
* path. Provides a fast-path for some internal cases.
*/
URI(String scheme, String path) {assert validSchemeAndPath(scheme, path);this.scheme = scheme;this.path = path;
}private static boolean validSchemeAndPath(String scheme, String path) {try {URI u = new URI(scheme + ":" + path);return scheme.equals(u.scheme) && path.equals(u.path);} catch (URISyntaxException e) {return false;}
}//静态工厂方法,最终调用的是URI(String str)
public static URI create(String str) {try {return new URI(str);} catch (URISyntaxException x) {throw new IllegalArgumentException(x.getMessage(), x);}
}
这种获取实例的方法,直接查看源码便知道有哪些了
这里就说明一下一些参数的含义:
- scheme:协议
- auth