欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

026.7 网络编程 URL对象

程序员文章站 2022-03-26 09:25:02
通过一个程序理解Java的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);