Abstract class URLConnection is a superclass of all classes that represents a communication link between an application and a URL. Instances of this class can be used to read and write resources referenced by this URL. In general, creating a connection to a URL requires several steps:
OpenConnection () operates on parameters that affect the connection to a remote resource. Connect () interacts with the resource; Query header fields and content.
- Create a Connection object by calling the OpenConnection method on the URL.
- Action set parameters and general request properties.
- Use the Connect method to establish an actual connection to the remote object.
- The remote object becomes available. The header fields and contents of the remote object become accessible.
Importjava.net.*;ImportJava.io.*;Importjava.util.Date; Public classUrlconnectiondemo { Public Static voidMain (string[] args)throwsexception{//Urlconnectiondemo Urlconnectiondemo = new Urlconnectiondemo (); intC; URL HP=NewURL ("http://www.hao123.com/"); URLConnection Hpcon=hp.openconnection (); System.out.println ("Date:" +NewDate (Hpcon.getdate ())); System.out.println ("Content-type:" +Hpcon.getcontenttype ()); System.out.println ("Expires:" +hpcon.getexpiration ()); System.out.println ("Last-modified:" +NewDate (Hpcon.getlastmodified ())); intlen=hpcon.getcontentlength (); System.out.println ("Content-length:" +Len); if(len>0) {System.out.println ("= = = Content = = ="); InputStream input=Hpcon.getinputstream (); intI=Len; while((C=input.read ())!=-1 && (--i>0) {System.out.print (Char) c); } } ElseSystem.out.println ("No Content available!"); } }
Operation Result:
Date:mon 11:07:02 CSTContent-type:text/1188443222000 last-modified:fri 2412 : 29:00 CSTcontent-length:44966=== content === ...
Java-urlconnection class explanation