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();
时间: 2024-11-04 23:57:23