First, introduce the URLConnection class:
The OpenConnection () method in the URL class can generate a URLConnection object, and an instance of the URLConnection class can be used to read and write the resources referenced by this URL.
In the network programming work, Java's urlconnection is a commonly used class, it provides a very convenient interface, as long as provides the host which needs to connect the URL address, uses the URL class OpenConnection () method, you can get a HttpURLConnection object, where the HttpURLConnection class is a subclass of the URLConnection class, and then analyze the HTTP content and complete the related tasks on this basis. In this way, users do not have to consider the bottom of the implementation details, avoid cumbersome socket class code writing, so more commonly used.
URLConnection Common Method String Getheaderfield (string name) returns the value of the specified header field. InputStream getInputStream () returns the input stream read from this open connection. String getcontentencoding () returns the value of the Content-encoding header field. int Getcontentlength () returns the value of the Content-length header field. String getContentType () returns the value of the Content-type header field. Long GetDate () returns the value of the Date header field.
public class InetAddress {public
static void Main (string[] args) {
try {
System.out
. println (" Use the URL class to download the Shenzhen University homepage http://www.szu.edu.cn, and statistics download the page file size ");
URL url = new URL ("http://www.szu.edu.cn");
InputStream in = Url.openstream ();
FileOutputStream fout = new FileOutputStream (New File (
"C:/users/97617/workspace/inetaddress/src/com/imooc",
"szu.html"));
int a = 0;
while (a >-1) {
a = In.read ();
Fout.write (a);
}
catch (IOException e) {
System.out.println ("Download the home of Shenzhen University http://www.szu.edu.cn failed") by using a URL class;
}
File File = new file (
"c:/users/97617/workspace/inetaddress/src/com/imooc/szu.html");
SYSTEM.OUT.PRINTLN ("File size is:"
+ new DecimalFormat ("#.00"). Format (File.length ()/1024.00)
+ "K");
}