Java網絡編程(二)
**************************IP地址類---InetAddress***************************
演示代碼:
package com.chapter15;
import java.net.InetAddress;
/**
* 公司:藍橋軟件學院 作者:zhangzy 時間:2017年7月28日 下午2:08:21 功能:演示代表IP地址的類 InetAddress
*/
public class TestInetAddress {
public static void main(String[] args) throws Exception {
// 根據主機名來獲取對應的InetAddress實例
InetAddress ip = InetAddress.getByName("www.lanqiao.org");
// 判斷是否可達
System.out.println("lanqiao是否可達:" + ip.isReachable(10000));// lanqiao是否可達:true
// 獲取該InetAddress實例的IP字符串
System.out.println(ip.getHostAddress());// 123.57.174.45
// 根據原始IP地址來獲取對應的InetAddress實例
InetAddress local = InetAddress
.getByAddress(new byte[] { 127, 0, 0, 1 });
System.out.println("本機是否可達:" + local.isReachable(5000));// 本機是否可達:true
// 獲取該InetAddress實例對應的全限定域名
System.out.println(local.getCanonicalHostName());// 127.0.0.1
}
}
************************URLDecoder和URLEncoder工具類***************************
這兩個工具類可以把普通的字符串轉換成application/x-www-form-urlencoded字符串
URLDecoder 解碼
URLEncoder 可以把普通字符串編碼成 URL編碼的字符串
普通字符串: 藍橋
application/x-www-form-urlencoded字符串: %E8%93%9D %E6%A1%A5
URL編碼、百分號編碼
演示代碼:
package com.chapter15;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
public class 演示URLEncoder和URLDecoder {
public static void main(String[] args) {
/*try {
//URL編碼的字符串 解碼成 普通字符串
String str = URLDecoder.decode("%E8%93%9D%E6%A1%A5", "utf-8");
System.out.println(str);
} catch (UnsupportedEncodingException e) {
System.out.println("沒有指定的字符編碼");
e.printStackTrace();
}*/
String urlStr;
try {
urlStr = URLEncoder.encode("軟件", "gbk");
System.out.println(urlStr);
} catch (UnsupportedEncodingException e) {
System.out.println("沒有指定的字符編碼");
e.printStackTrace();
}
}
}
Java網絡編程(二)