URL openStream

本文探讨了Java中URL类的基本用法及其与URLConnection的关系。重点介绍了如何使用URL类建立网络连接并读取数据,同时讨论了在网络编程中缓冲数据的重要性及安全限制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

OReilly.Java.I.O.2nd.Edition
5.1. URLs




InputStream in = null;
try {
URL u = new URL("http://www.oreilly.com/");
in = u.openStream();
for (int c = in.read(); c != -1; c = in.read()) {
System.out.write(c);
}
} catch (MalformedURLException ex) {

} finally {
if (in != null)
in.close();
}





Most [b]network[/b] connections, even on LANs, are [b]slower and less reliable[/b] sources of data than files. Connections across the Internet are even [b]slower and less reliable[/b], and connections through a modem are slower and less reliable still. [b]One way to enhance performance under these conditions is to buffer the data: to read as much data as you can into a temporary storage array inside the class[/b], then parcel it out as needed. In the next chapter, you'll learn about the [b]BufferedInputStream[/b] class that does exactly this.

Untrusted code running [b]under the control of a security manager[/b] e.g., [b]applets[/b] that run inside a web browser are normally allowed to connect [b]only to the host they were downloaded from[/b]. This host can be determined from the URL returned by the getCodeBase( ) method of the Applet class. Attempts to [b]connect to other hosts throw security exceptions[/b]. You can create URLs that point to other hosts, but you may not download data from them using openStream( ) or any other method. (This security restriction for applets applies to any network connection, regardless of how you get it.)


5.2. URL Connections

[b]URL connections are closely related to URLs[/b], as their name implies. Indeed, you get a reference to a URLConnection by using the openConnection( ) method of a URL object; in many ways, the URL class is only a wrapper around the URLConnection class. URL connections [b]provide more control over the communication between the client and the server[/b].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值