URLConnection : Java Glossary

go to home page U words local find full screen, hide local find menu Google search web for more information on this topic jump to foot of page translate this page with Babelfish by Roedy Green ©1996-2009 Canadian Mind Products
index page for letter ⇒ punctuation 0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z (all)
URLConnection
A java.net.URL is just the name of a resource, usually a file on a remote website, but it can be a local file, a file in a jar or many other things. java.net.URLs don’t establish any sort of electrical connection to the resource. That is the job of java.net.URLConnection.

You create the URLConnection, then set modifiers such as setUseCaches( false ), then call connect, the start reading or writing using methods to read header such as getContentType or getContent to read the body of the message.

connect is a bit confusing, since it will get called for you automatically if you leave it out, and you can’t set any modifiers once it has been called, whether you called it, or it was called automatically. It forgiving. If you call it and you are already connected, it is just ignored.

One slightly peculiar thing about URLConnection c = url.getConnection () is that URLConnection is an abstract class. When you use url.openConnection () you will get say an HttpURLConnection subclass of URLConnection object or a JarURLConnection object, since there is no such thing as a plain URLConnection object. If you cast your URLConnection result to a HttpURLConnection, you have access to extra methods.

URLConnection is tricky in that some of its methods will work only before you call connect e.g. setDoInput, setDoOutput and setUseCaches while other methods will only work after, e.g. getContent, getHeaderField, getInputStream and getOutputStream.

getContent is a mysterious method. It gets you a chunk of data, e.g. a jpg file (ImageProducer), a chunk of an email etc. You have to cast the Object it gives you to whatever it was you were expecting based on the mime type in the message header. It is probably easiest just find out what you get by experiment, by displaying the classane of the object you get. Some possiblitites include:

For examples of use, see the File I/O Amanuensis and set the source or target to URL.
Sun’s Javadoc on the URLConnection class : available:
Sun’s Javadoc on the HttpURLConnection class : available:

CMP homejump to top
CMP logo
feedback Please email your feedback for publication, errors, omissions, broken/redirected link reports
and suggestions to improve this page to Roedy Green : feedback email
made with CSS
HTML Checked!
ICRA ratings logo
mindprod.com IP:[65.110.21.43]
Your face IP:[38.103.63.58]
You are visitor number 17,209.
You can get a fresh copy of this page from: or possibly from your local J: drive (Java virtual drive/mindprod.com website mirror)
http://mindprod.com/jgloss/urlconnection.html J:\mindprod\jgloss\urlconnection.html