首页 > 代码库 > Java.net.URL学习总结
Java.net.URL学习总结
String host = "www.java2s.com"; String file = "/index.html"; String[] schemes = {"http", "https", "ftp", "mailto", "telnet", "file", "ldap", "gopher", "jdbc", "rmi", "jndi", "jar", "doc", "netdoc", "nfs", "verbatim", "finger", "daytime", "systemresource"}; for (int i = 0; i < schemes.length; i++) { try { URL u = new URL(schemes[i], host, file); System.out.println(schemes[i] + " is supported/r/n"); } catch (Exception ex) { System.out.println(schemes[i] + " is not supported/r/n"); } }
结果为
http is supported/r/n https is supported/r/n ftp is supported/r/n mailto is supported/r/n telnet is not supported/r/n file is supported/r/n ldap is not supported/r/n gopher is not supported/r/n jdbc is not supported/r/n rmi is not supported/r/n jndi is not supported/r/n jar is supported/r/n doc is not supported/r/n netdoc is supported/r/n nfs is not supported/r/n verbatim is not supported/r/n finger is not supported/r/n daytime is not supported/r/n systemresource is not supported/r/n
URL.getContent()返回的是一个Object对象,可以用.getClass().getName()获得这个对象实际的名字,如下代码:(这里在创建URL对象的时候,向构造方法里传的值,必须要以http://这个协议开头,要不会抛出异常:java.net.MalformedURLException: no protocol: www.baidu.com)
URL url = new URL("http://www.baidu.com"); Object content = url.getContent(); System.out.println(content.getClass().getName());
以上代码打印的是:
sun.net.www.protocol.http.HttpURLConnection$HttpInputStream
可以利用URL的openConnection方法,返回一个URLConnection对象,此对象可以用来获取输入流。
URL url = new URL("http://www.baidu.com"); URLConnection urlConnection = url.openConnection(); InputStream inputStream = urlConnection.getInputStream(); int c ; while ((c = inputStream.read()) != -1) { System.out.println((char)c); } inputStream.close();
或者用URL本身的openStream方法获取输入流。
URL url = new URL("http://www.baidu.com"); //打开到此 URL 的连接并返回一个用于从该连接读入的 InputStream。 InputStream in = url.openStream(); int c; while ((c = in.read()) != -1) System.out.print(c); in.close();
Java.net.URL学习总结
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。