https://blog.csdn.net/it_cookie_sam/article/details/55657708
转
java.net.url对象
感谢博主的用心编写
原文链接:http://blog.csdn.net/witsmakemen/article/details/6989010
一、用JAVA实现URL
在JAVA中,Java.net包里面的类是进行网络编程的,其中java.net.URL类和java.net.URLConection类使编程者方便地利用URL在Internet上进行网络通信。1、创建URL对象
URL类有多种形式的构造函数:
![](https://i-blog.csdnimg.cn/blog_migrate/4f1150b881333f12a311ae9ef34da474.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/4f1150b881333f12a311ae9ef34da474.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/4f1150b881333f12a311ae9ef34da474.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/4f1150b881333f12a311ae9ef34da474.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/4f1150b881333f12a311ae9ef34da474.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/4f1150b881333f12a311ae9ef34da474.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/4f1150b881333f12a311ae9ef34da474.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/4f1150b881333f12a311ae9ef34da474.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/4f1150b881333f12a311ae9ef34da474.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/4f1150b881333f12a311ae9ef34da474.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/4f1150b881333f12a311ae9ef34da474.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/4f1150b881333f12a311ae9ef34da474.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/4f1150b881333f12a311ae9ef34da474.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/4f1150b881333f12a311ae9ef34da474.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/4f1150b881333f12a311ae9ef34da474.gif)
2、获取URL对象的属性
getDefaultPort(): 返回默认的端口号。
getFile(): 获得URL指定资源的完整文件名。
getHost(): 返回主机名。
getPath(): 返回指定资源的文件目录和文件名。
getPort(): 返回端口号,默认为-1。
getProtocol(): 返回表示URL中协议的字符串对象。
getRef(): 返回URL中的HTML文档标记,即#号标记。
getUserInfo: 返回用户信息。
toString: 返回完整的URL字符串。
二、Internet寻址
java.net包可以用32位int形式来操作32位的IP地址(即Internet主机地址)。类InetAddress实际上是可以把Internet地址换算成代表该地址的对象。Java就是靠这个类来显示Internet地址已经相关信息的。
InetAddress有以下常用方法:
getAddress(): 返回IP地址的字节形式。
getAllByName(): 返回指定主机名的IP地址。
getbyAddress(): 返回指定字节数组的IP地址形式。
getByName(): 返回指定主机名的IP地址对象。
getHostAddress(): 返回主机地址的字符串形式。
getLocalHost(): 返回当前主机名。
hastCode(): 返回InetAddress对象的哈希码。
toString: 返回地址转换成的字符串。
InetAddress类没有提供返回构造函数,所以不能用new()方法来创建它的对象,而只可以调用静态方法getLocalHost()、getByName()、getByAddress()等来生成InetAddress类的实质。