Program to send HTTP Request to Web server

Below is an example on how to send an HTTP request to any web Server like Tomcat, Glass Fish, Web Logic, Web Sphere. Below Java program acts like a simple Web Browser, which sends HTTP GET or POST Request to Web Server, and prints response( from Web Server) to console.

HTTP Protocol is further dependent on TCP/IP Protocol.
i..e HttpURLConnection further uses underlying Sockets to interact with Web Server.

Difference between HttpURLConnection and HttpsURLConnection

Both HttpURLConnection and HttpsURLConnection classes are in java.net package.
HttpURLConnection uses unsecured version of HTTP(Hyper Text Transfer Protocol), where as HttpsURLConnection is secured version of HTTP Protocol.

Both HttpURLConnection and HttpsURLConnection can use any of the HTTP methods, either GET or POST method.

Difference between GET and POST HTTP Methods

HTTP POST
Data is sent thru URL
Eg: /abc.jsp?mytext=fdfsdfsdf&pwd=fgfdgfdgfd
Data is sent internally
Only limited data can be submitted Unlimited data can be submitted to server program
Unsecured compared to POST Secured compared to GET

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.MalformedURLException;

import javax.net.ssl.HttpsURLConnection;

public class HttpURLConnectionEg {

	private final String USER_AGENT = "Test Client";

	public static void main(String[] args) throws Exception {

	HttpURLConnectionEg http = new HttpURLConnectionEg();

	System.out.println("Sending Http GET request to URL:");
	http.sendGet();
	System.out.println("---------------------------------");
	System.out.println("Send Http POST request to URL:");
	http.sendPost();

	}

	// HTTP GET request example
	private void sendGet() throws Exception {

	String url = "http://localhost/index.php";

	URL obj = new URL(url);
	HttpURLConnection con = (HttpURLConnection) obj.openConnection();

	// optional, default Request method is GET
	con.setRequestMethod("GET");

	//add request header
	con.setRequestProperty("User-Agent", USER_AGENT);

	int responseCode = con.getResponseCode();
        //responseCode is numeric value of HTTP response, can be 2XX,3XX,4XX or 5XX

	System.out.println("Sending GET request to URL : " + url);
	System.out.println("Response Code : " + responseCode);

	BufferedReader in = new BufferedReader(
		new InputStreamReader(con.getInputStream()));
	String inputLine;
	StringBuffer response = new StringBuffer();

	while ((inputLine = in.readLine()) != null) {
		response.append(inputLine);
	}
	in.close();

	//print result
	System.out.println(response.toString());

	}

	// HTTP POST request example
	private void sendPost() throws MalformedURLException,IOException{

	String url = "https://localhost/index.php";
	URL obj = new URL(url);
	HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

	//set request method
	con.setRequestMethod("POST");

        //set header values, first parameter is header name, second parameter is header value
	con.setRequestProperty("User-Agent", USER_AGENT);

	String urlParameters = "a=1234&b=5678&c=65465&d=7263543";

	// Send post request
	con.setDoOutput(true);
	DataOutputStream wr = new DataOutputStream(con.getOutputStream());

        //write the bytes of Request Parameters, to the Server
	wr.writeBytes(urlParameters);
	wr.flush();
	wr.close();

	int responseCode = con.getResponseCode();
	System.out.println("Sending POST request to URL : " + url);
	System.out.println("Post parameters : " + urlParameters);

        //responseCode is numeric value of HTTP response, can be 2XX,3XX,4XX or 5XX
	System.out.println("Response Code : " + responseCode);

        //Create BufferedReader, with the input stream of the response from Web Server
	BufferedReader in = new BufferedReader(
		new InputStreamReader(con.getInputStream()));
	String inputLine;
	StringBuffer response = new StringBuffer();

	while ((inputLine = in.readLine()) != null) {
		response.append(inputLine);
	}
	in.close();

	//Now the response from Web Server, is in response StringBuffer
        //Then print response on the console
	System.out.println(response.toString());

	}

}

You may also like to read:
What is a network port?

Java Networking

Network programming refers to writing programs that execute across multiple devices (computers), in which the devices are all connected to each other using a network.

java.net package of the J2SE APIs contains classes for Network or Socket Programming.

TCP

: TCP stands for Transmission Control Protocol, which allows for reliable communication between two applications. TCP is typically used over the Internet Protocol, which is referred to as TCP/IP. TCP is Connection oriented Protocol. All packets are traversed thru the connection created between devices.

UDP

: UDP stands for User Datagram Protocol, a connection-less protocol that allows for packets of data to be transmitted between applications. Packets traverse thru multiple paths, between devices. There is no guarantee in the order of packets received.

IP Address

: Each device on network is identified by IP Address. There are two versions of IP Address, IPv4 and IPv6. IPv4 is 32 bit, and IPv6 is 128 bit IP Address.

Port Numbers

: A device will have multiple(thousands) of Network port numbers. Purpose of port numbers is multiple programs(on a machine) can simultaneously send/receive data.
For example you may want to use Chat Application, Email Client, Web Browser etc… simultaneously. And those Applications may need to send and receive data over network at same time. For which each Application is binded to a port number, hence multiple port numbers are required, for Applications to simultaneously read and write data to network.Hence, if multiple port numbers are not available on device, then only one Application on Device can connect to Network.

TCP Sockets
TCP Sockets

Standard Port Numbers:
80 – HTTP (Protocol used by Web Browser and WebServer) Stands or Hyper Text Transfer Protocol
443 – HTTPS(also used by Web Browser and Web Server, for secured communication)
25 – SMTP(Simple Mail Transfer Protocol)
110 – POP3(Post Office Protocol),etc…

DNS(Domain Name Server)

converts domain name to IP Address. IP Address of Machines are required to Transfer data between Machines in a Network.

java networking
java networking

java.net

How to create TCP sockets between Client and Server Machines

ServerSocket class is used by server applications to obtain a port and listen for client requests.
Socket represents the socket that both the client and server use to communicate with each other. The client obtains a Socket object by instantiating one, whereas the server obtains a Socket object from the return value of the accept() method.

Socket and ServerSocket support both versions of IP Address IPv4 and IPv6.

How to create UDP sockets between Machines

DatagramSocket: Each packet sent or received on a datagram socket is individually addressed and routed. Multiple packets sent from one machine to another may be routed differently. Datagram packets may be received in different order, than sent.
DatagramPacket: Data is sent thru DatagramPacket over DatagramSocket

How to send and receive HTTP request/response, from/to Web server?

URLConnection – Base class of HttpURLConnection
HttpURLConnection – sends HTTP Request(GET or POST method) to a Web Server, and gets the response.
HttpsURLConnection – same as HttpURLConnection, but this is secured version.

You may also like to read:
RMI in Java
Java Socket Client example
ServerSocket example