一、InetAddress
1、java提供InetAddress类代表IP地址,InetAddress下含有两个子类:
Inet4Address、Inet6Address,他们分别代表IPv4地址和IPv6地址。
2、InetAddress类没有构造器,提供如下两个静态方法来获取InetAddress实例:
getByName(String host):根据主机获取对应的InetAddress对象;
getByAddress(byte [ ] addr):根据原始IP地址来获取对应的InetAddress对象。
3、InetAddress提供如下三种方法获取InetAddress实例对应的IP地址和主机名:
String getCanonicalHostName():获取此IP地址的全限定域名;
String getHostAddress():返回该InetAddress实例对应的IP地址字符串;
String getHostName():获取此IP地址的主机名。
4、InetAddress类的其它方法:
getLocalHost():获取本机IP地址对应的InetAddress实例;
isReachable():用于测试是否可以到达该地址。
代码示例:
package defaultpackage;
import java.net.InetAddress;
public class InetAddressTest {
public static void main(String [] args ) throws Exception{
//根据主机名来获取对应的InetAddress实例
InetAddress ip = InetAddress.getByName("www.sina.com");
//判断是否可达
System.out.println("sina是否可达:"+ip.isReachable(2000));
//获取该InetAddress实例的IP字符串
System.out.println(ip.getHostAddress());
//根据原始的IP地址来获取对应的InetAddress实例
InetAddress local = InetAddress.getByAddress(new byte[]{127,0,0,1});
System.out.println("本机是否可达:"+local.isReachable(5000));
//获取该InetAddress实例对应的全限定域名
System.out.println(local.getCanonicalHostName());
}
}
二、URLDecoder和URLEncoder
URLDecoder和 URLEncoder用于完成普通字符串和application/x-www-form-urlencoded
MIME字符串之间的相互转换。
1、URLDecoder类包含一个decode(String s,String enc)静态方法:将看上去是乱码的
application/x-www-form-urlencoded MIME字符串转成普通字符串;
2、URLEncoder类包含一个encoder(String s,String enc)静态方法:将普通字符串转换成
application/x-www-form-urlencoded MIME字符串。 代码示例:
public class URLDecoderTest{
public static void main (String [ ] args) throws Exception{
//将application/x-www-form-urlencoded字符串转换为普通字符串
String keyWord = URLDecoder.decode("%E6%9D%8E%E5%88%9A+j2ee",
"UTF-8");
System.out.println(keyWord);
//将普通字符串转换为application/x-www-form-urlencoded字符串
String urlStr = URLEncoder.encode("ROR敏捷开发最佳指南","GBK");
System.out.println(urlStr);
}
}
三、URL和URLConnection
URL(Uniform Resource Locator)对象代表统一资源定位器,
格式为:protocol://host:port/resourceName
URL类的一些方法:
String getFile():获取此URL的资源名
String getHost():获取此URL的主机名
String getPath():获取此URL的路径部分
int getPort():获取此URL的端口号
String getProtocol():获取此URL的协议名称
String getQuery():获取此URL的查询字符串部分
URLConnection openConnection():返回一个URLConnection对象,它表示到URL
所引用的远程对象的连接。
InputStream openStream():打开与此URL的连接,并返回一个用于读取该URL资源
的InputStream。