---
title: "URL openStream"
author: "wutao8818"
date: "2009-04-14T17:26:46Z"
tags: ["C", "C#", "C++", "Security", "performance"]
slug: "url-openstream"
draft: false
lastmod: "2009-04-14T18:02:11Z"
id: 367303
url: "https://wutaoo.iteye.com/blog/367303"
---

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

```java



		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 **network** connections, even on LANs, are **slower and less reliable** sources of data than files. Connections across the Internet are even **slower and less reliable**, and connections through a modem are slower and less reliable still. **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**, then parcel it out as needed. In the next chapter, you'll learn about the **BufferedInputStream** class that does exactly this.

Untrusted code running **under the control of a security manager** e.g., **applets** that run inside a web browser are normally allowed to connect **only to the host they were downloaded from**. This host can be determined from the URL returned by the getCodeBase( ) method of the Applet class. Attempts to **connect to other hosts throw security exceptions**. 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

**URL connections  are closely related to URLs**, 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 **provide more control over the communication between the client and the server**.