当前位置: 代码迷 >> 综合 >> URL、URLConnection、InetAddress 这几个类的基本使用方法
  详细解决方案

URL、URLConnection、InetAddress 这几个类的基本使用方法

热度:68   发布时间:2023-12-14 01:14:54.0
package cn.bl.net;import java.io.InputStream;
import java.net.URL;import org.junit.Test;public class Demo1_URL {@Testpublic void test() {URL url;try {url = new URL("https://blog.csdn.net/qq_38238041");System.out.println(url.toString());//也就是这个网址System.out.println(url.getPort());//没设置就返回-1System.out.println(url.getDefaultPort());//返回默认端口  --  443System.out.println(url.getProtocol());//https - 协议System.out.println(url.getHost());//blog.csdn.netInputStream in = url.openStream();//将网页的html读取出来了byte[]b = new byte[512];int len = -1;while((len = in.read(b)) !=-1) {System.out.println(new String(b, 0, len));}} catch (Exception e) {e.printStackTrace();}}
}
package cn.bl.net;import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;import org.junit.Test;public class Demo2_URLConnection {@Testpublic void test() {try {URL url = new URL("https://blog.csdn.net/qq_38238041");URLConnection con = url.openConnection();System.out.println("返回资源文件的长度:"+con.getContentLength());System.out.println("返回资源文件的类型:"+con.getContentType());} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}
}
package cn.bl.net;import java.net.InetAddress;import org.junit.Test;public class Deom3_InetAddress {@Testpublic void test() throws Exception {InetAddress address = InetAddress.getByName("blog.csdn.net");System.out.println(address.getHostAddress());//39.96.132.69System.out.println(address.isSiteLocalAddress());//falseSystem.out.println(address.getHostName());//blog.csdn.net}
}

 

  相关解决方案