Java的网络类 在java.net 包中
URL(Uniform resouce locator)统一资源定位符,表示互联网上某一资源的定位符 包括协议表示符,资源名字(主机名,文件名,端口号,引用)对于http协议默认的监听端口号就是80
我们更希望能够通过这个URL访问页面上的内容,但是注意的是只能获取文本或者绝对路径的图片, 相对地址的东西获取不到。
一般又两种方式获取到URL地址指向的页面的内容
// 第一种 :首先建立一个连接,然后数据读取到流中,然后对流进行操作
URLConnection urlConnect = url.openConnection();
InputStream in = urlConnect.getInputStream();
// 第二种: 实际上就是将上面的两步合为一步
InputStream in = url.openStream();
public class URLTest {
public static void main(String[] args) throws Exception {
// URL url = new URL("https://blog.csdn.net/woshiluoye9/article/details/62217199");
URL url = new URL("https://www.baidu.com/");
// 下面的这些都是通过分析URL的地址实现的,并没有联网真正的访问URL所在的真实地址
String protocal = url.getProtocol(); // http 获取协议类别
int post = url.getPort(); // 获取端口号
String file = url.getFile(); // 获取文件名
String host = url.getHost(); // 网址
String ref = url.getRef(); //
System.out.println(protocal + " " + post +" "+host+" " + file +" "+ ref );
// 输出为 http -1 blog.csdn.net /woshiluoye9/article/details/62217199 null
//我们更希望能够通过这个URL访问页面上的内容,只能获取文本或者绝对路径的图片, 相对地址的东西获取不到
// 下面是其的实现
URLConnection urlConnect = url.openConnection(); // 首先建立一个连接
InputStream in = urlConnect.getInputStream(); // 将网页上的内容读取到一个流中
// 或者另一种方法,等同于上面的两句
// InputStream in = url.openStream();
byte[] byteArray = new byte[2048];
int length = 0;
FileOutputStream fileOut = new FileOutputStream("G:\\aa.txt ");
while ( -1 != (length = in.read(byteArray,0,byteArray.length))){
fileOut.write(byteArray);
}
in.close();
fileOut.close();
}
}
InetAddress : 对IP地址的操作
public class IpAddressTest {
public static void main(String[] args) throws Exception {
InetAddress ip = InetAddress.getLocalHost(); // 获取本机的ip
System.out.println(ip);
InetAddress ip2 = InetAddress.getByName(“www.baidu.com”); // 根据域名获取 ip
System.out.println(ip2);
InetAddress[] ip3 = InetAddress.getAllByName(“www.baidu.com”); // 根据域名获取全部的ip,
System.out.println(ip3.length);
}
}