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地址.