026.7 网络编程 URL对象

通过一个程序理解Java的url对象。

String str_url = "http://127.0.0.1:8080?name=xxx";
URL url = new URL(str_url);
System.out.println(url.getProtocol());  //协议
System.out.println(url.getHost());     //主机
System.out.println(url.getPort());
System.out.println(url.getPath());
System.out.println(url.getFile());    //?name=xxx
System.out.println(url.getQuery());   //name=xxx

//通过openConnection;获取到该远程资源的连接对象
URLConnection conn = url.openConnection();
System.out.println(conn);

//调用连接对象的读取方法,准备读取资源
InputStream in = conn.getInputStream();

byte[] buf = new byte[1024];
int len = 0;

len = in.read(buf);

String res = new String(buf,0,len);

System.out.println(len);
System.out.println(res);

 

你可能感兴趣的:(026.7 网络编程 URL对象)