URLConnections are closely related to URLs. Indeed,you get a reference to a URLConnection by using the openConnection() method of an URL object. In many ways,the URL class is only a wrapper around the URLConnection class. URLConnections provide more control over the communication between the client and the server. In particular,URLConnections provide not just input streams by which the client can read data from the server,but also output streams to send data from the client to the server.
Reading data
There are several steps:
- The URL object is constructed
- The openConnection() method of the URL object creates the URLConnection object
- The parameters for the connection and the request properties that the client sends to the server are set up
- The connect() method makes the connection to the server,perhaps using a socket for a network connection or a file input stream for a local connection. The response header information is read from the server
- Data is read from the connection using the input stream returned by getInputStream() or a content handler returned by getContent(). Data can be sent to the server using the output stream provided by getOutputStream()
This scheme is very much based on the HTTP protocol. It does not fit other schemes that have a more interactive “request,response,request,response,request,response”pattern instead of HTTP/1.0′s “single request,single response,close connection”pattern. In particular,FTP doesn’t really fit this pattern.
Writing data
Writing data to a URLConnection is similar to reading data
- Construct the URL object
- Call the openConnection() method of the URL object to create the URLConnection object
- Pass true to setDoOutput() to indicate that this URLConnection will be used for output
- If you also want to read input from the stream,invoke setDoInput(true) to indicate that this URLConnection will be used for input
- Create the data you want to send,preferably as a byte array
- Call getOutputStream() to get an output stream object. Write the byte array calculated in previous step onto the stream
- Close the output stream
- Call getInputStream() to get an input stream object. Read and write it as usual
I am going to post example which shows how to read data from URLConnection:
import java.io.IOException;import java.io.InputStream;import java.net.URL;import java.net.URLConnection;public class Main{ public static void main(String[] args) throws IOException{ InputStream inputStream = null; try{ URL url = new URL("http://thedevelopersinfo.com/"); URLConnection connection = url.openConnection(); inputStream = connection.getInputStream(); for (int c = inputStream.read();c != -1;c = inputStream.read()){System.out.write(c); } } catch (IOException ex){ ex.printStackTrace(); } finally{ if (inputStream != null){inputStream.close(); } } }}
Download code from this post.
No related posts.

Recent Comments