Java 中网络相关 API 的应用
InetAddress的应用
1 import java.net.InetAddress; 2 import java.net.UnknownHostException; 3 import java.util.Arrays; 4 5 public class Test01 { 6 7 public static void main(String[] args) throws UnknownHostException { 8 //获取本机的InetAddress实例 9 InetAddress address = InetAddress.getLocalHost(); 10 System.out.println("计算机名:" + address.getHostName()); 11 System.out.println("IP地址:" + address.getHostAddress()); 12 byte[] bytes = address.getAddress(); //获取字节数组形式的IP地址 13 System.out.println("字节数组形式的IP地址:" + Arrays.toString(bytes)); 14 System.out.println(address); //直接输出InetAddress对象 15 System.out.println(); 16 17 //根据机器名获取InetAddress实例 18 //InetAddress address2 = InetAddress.getByName("DESKTOP-1GQCD7C"); 19 InetAddress address2 = InetAddress.getByName("10.4.44.26"); 20 System.out.println("计算机名:" + address2.getHostName()); 21 System.out.println("IP地址:" + address2.getHostAddress()); 22 } 23 24 }
以上来自慕课网
菜鸟教程:www.runoob.com/java/java-networking.html
URL的应用
URL常用方法
1 import java.net.MalformedURLException; 2 import java.net.URL; 3 4 /* 5 * URL常用方法 6 */ 7 8 public class Test02 { 9 public static void main(String[] args) { 10 try { 11 //创建一个URL实例 12 URL imooc = new URL("http://www.imooc.com"); 13 //?后面表示参数,#后面表示锚点 14 URL url = new URL(imooc,"/index.html?username:tom#test"); 15 System.out.println("协议:" + url.getProtocol()); 16 System.out.println("主机:" + url.getHost()); 17 //如果未指定端口号,则使用默认的端口号,此时getPort()方法返回值为-1 18 System.out.println("端口:" + url.getPort()); 19 System.out.println("文件路径:" + url.getPath()); 20 System.out.println("文件名:" + url.getFile()); 21 System.out.println("相对路径:" + url.getRef()); 22 System.out.println("查询字符串:" + url.getQuery()); 23 } catch (MalformedURLException e) { 24 e.printStackTrace(); 25 } 26 } 27 }
使用URL读取网页内容
1.通过URL对象的openStream()方法可以得到指定资源的输入流
2.通过输入流可以读取、访问网络上的数据
1 import java.io.BufferedReader; 2 import java.io.IOException; 3 import java.io.InputStream; 4 import java.io.InputStreamReader; 5 import java.net.MalformedURLException; 6 import java.net.URL; 7 8 /* 9 * 使用URL读取网页内容 10 */ 11 public class Test03 { 12 public static void main(String[] args) { 13 try { 14 //创建一个URL实例 15 URL url = new URL("http://www.baidu.com"); 16 //通过URL的openStream方法获取URL对象所表示的资源的字节输入流 17 InputStream is = url.openStream(); 18 //将字节输入流转换为字符输入流 19 InputStreamReader isr = new InputStreamReader(is, "utf-8"); 20 //为字符输入流添加缓冲 21 BufferedReader br = new BufferedReader(isr); 22 String data = br.readLine();//读取数据 23 while (data != null) {//循环读取数据 24 System.out.println(data);//输出数据 25 data = br.readLine(); 26 } 27 br.close(); 28 isr.close(); 29 is.close(); 30 } catch (MalformedURLException e) { 31 e.printStackTrace(); 32 } catch (IOException e) { 33 e.printStackTrace(); 34 } 35 } 36 }