码迷,mamicode.com
首页 > 编程语言 > 详细

Java.net.URL学习总结

时间:2017-08-04 16:10:29      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:java   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学习总结

标签:java   url   学习总结   

原文地址:http://10750710.blog.51cto.com/10740710/1953584

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!