java 为网络支持提供了java.net包.
1. 该包下的URL和URLConnection类提供了以编程方式访问Web服务的功能
2. URLDecoder和URLEncoder提供普通字符串和application/x-www-form-urlencoded MIME
3. InetAddress类代表IP地址
程序清单:InetAddressTest.java
import java.net.InetAddress;
public class InetAddressTest {
public static void main(String[] args) throws Exception {
InetAddress ia = InetAddress.getByName("www.163.com");
System.out.println("是否可到达:" + ia.isReachable(5000));
//获取ia对象的Ip和主机名
System.out.println(ia.getHostAddress() + "~" +ia.getHostName());
//getCanonicalHostName返回结果是Ip地址
System.out.println(ia.getCanonicalHostName());
InetAddress ia1 = InetAddress.getByAddress(new byte[] {10,17,8,61});
System.out.println("是否可到达:" + ia1.isReachable(5000));
System.out.println(ia1.getCanonicalHostName());
}
}
程序清单:URLDecoderTest.java
import java.net.URLDecoder;
import java.net.URLEncoder;
public class URLDecoderTest {
public static void main(String[] args) throws Exception
{
//将application/x-www-form-urlencoded字符串转换成普通字符串
//编码方式不同,结果不同
System.out.println("utf-8:" + URLEncoder.encode("未知数据" , "utf-8"));
System.out.println("GBK:" + URLEncoder.encode("未知数据" , "GBK"));
//将普通字符串转换成application/x-www-form-urlencoded字符串
System.out.println("utf-8:" + URLDecoder.decode("%E6%9C%AA%E7%9F%A5%E6%95%B0%E6%8D%AE", "utf-8"));
System.out.println("GBK:" + URLDecoder.decode("%CE%B4%D6%AA%CA%FD%BE%DD", "GBK"));
}
}
Q:上面的getCanonicalHostName()不知道有什么作用,不知道各位大虾有没有了解的?
上网google了一下,在C:\WINDOWS\system32\drivers\etc\hosts中设置了servername,就可以通过该方法获取到,否则返回IP地址.