Network Connection

Setting a network connection in JAVA is very easy. Today we will explain how to connect to a server, send a simple request to this server and read the response.

In this example, we are using the java.net.Socket class to connect to the host www.itcuties.com. We are connecting to the port 80, because this is the TCP port commonly used by the HTTP protocol.

Then, after opening the output stream, we are sending a HTTP GET request:

s_out.println("GET / HTTP/1.1");
s_out.println("Host: " + host + ":80");
s_out.println();

The format of the GET request is as follows:

 
GET <requested resource> <HTTP version>

Requested resource can be, for instance, an image on the page. In our example, we are simply requesting the source code of the page.

Java network connection code

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;

public class SimpleSocket
{
	public static void main(String [] args)
	{
		String host = "www.itcuties.com";
		int port = 80;

		PrintWriter s_out = null;
		BufferedReader s_in = null;

		System.out.println("Connecting to " + host + " on port " + port);
		Socket socket;

		try {
			socket = new Socket(host, port);

			System.out.println("Just connected to "
					+ socket.getRemoteSocketAddress());

			//Sending request
			s_out = new PrintWriter( socket.getOutputStream(), true);         

			s_out.println("GET / HTTP/1.1");
			s_out.println("Host: " + host + ":80");
			s_out.println();

			System.out.println("Message send!");

			s_in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

			//Getting response 
			System.out.println("Response from itcuties:\n");
			String response;
			while ((response = s_in.readLine()) != null) 
			{
				System.out.println( response );
			}

			//Closing the i/o streams
			s_out.close();
			s_in.close();

			//Closing the socket
			socket.close();

		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

It is important to specify the host one more time while sending the message.

The server receives following message:

GET / HTTP/1.1
Host: www.itcuties.com:80

Server responds with a HTTP response:

HTTP/1.0 200 OK

This is a standard answer for successful HTTP requests. Then it will send some information about the host (the data of the last modification etc.) and the source code that we requested. We are retrieving this information from the input stream and printing them on the console.

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Java by Example App is available at Google Play Store NOW