首页 > 代码库 > java net --------------------------------URL类
java net --------------------------------URL类
java net ---------------------------URL类
package java_net; import java.net.MalformedURLException; import java.net.URL; /* * 测试URL类 */ public class URL_Test { public static void main(String[] args) { try { //我们需要构造一个URL对象,构造方法有很多种 /* * 1、通过一个字符串构造URL对象 * public URL(String spec) throws MalformedURLException * Creates a URL object from the String representation. * This constructor is equivalent to a call to the two-argument constructor with a null first argument. * Parameters: * spec - the String to parse as a URL.(参数spec是一个可以代表网络地址的字符串) */ URL url1 = new URL("http://www.baidu.com"); System.out.println(url1.getAuthority()); /* * Gets the protocol name of this URL * 返回协议的名称 */ System.out.println("协议为:"+url1.getProtocol());//输出HTTP协议 /* * Gets the host name of this URL * 返回URL主机的名称 */ System.out.println("主机为:"+url1.getHost()); /* * Gets the path part of this URL. * 获取该URL地址的部分路径,如果不存在则为Null */ System.out.println(url1.getPath()); /* * Gets the file name of this URL. * 获取该地址的文件名称,未指定文件时则输出Null */ System.out.println(url1.getFile()); /* * Gets the anchor (also known as the "reference") of this URL. * Returns:the anchor (also known as the "reference") of this URL, or null if one does not exist * 返回锚点的值,不存在则为空 */ System.out.println(url1.getRef()); /* * Gets the port number of this URL. * 获取端口号,未设置则输出-1 */ System.out.println("端口号为:"+url1.getPort()); /* * Gets the default port number of the protocol associated with this URL. * If the URL scheme or the URLStreamHandler for the URL do not define a default port number, * then -1 is returned. * 返回协议默认的端口号,如果协议未定义端口号,返回-1 */ System.out.println(url1.getDefaultPort()); } catch (MalformedURLException e) { e.printStackTrace(); } } }
查看URL还有其他的方法,用时查阅API即可!
实例:
package java_net; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; /* * 通过URL在网络中读取数据 * 读取www.baidu.com主页 */ public class URL_Test02 { public static void main(String[] args) { try { //创建URL对象 URL url = new URL("https://www.baidu.com"); //获取URL对象的字节输入流 InputStream is = url.openStream(); //将字节输入流包装成字符输入流,注意要指定字符集 InputStreamReader isr = new InputStreamReader(is,"utf-8"); //将字符输入流包装成缓冲字符输入流 BufferedReader br = new BufferedReader(isr); //进行数据的读取 String line = br.readLine(); //循环读取数据 while(line!=null){ //打印读取到的数据 System.out.println(line); //再次读取 line = br.readLine(); } //关闭输入流 br.close(); isr.close(); is.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
本文出自 “@coder” 博客,请务必保留此出处http://smallcoder.blog.51cto.com/11941149/1859827
java net --------------------------------URL类
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。