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?

String object creation with and without new

What is the difference between below statements?
1. String str = “Hello”;
In this case, “Hello” memory is allocated during compile time itself, and str refers to “Hello” String literal address. Also note that

String str_a = “Hello”;
String str_b = “Hello”;
Both of these refers to same String object, and another object does not get created for str_b.

2. String str1 = new String(“Hello”);

In case of new version, “Hello” is dynamically allocated during run time, and “Hello” gets memory allocate on Heap.
String str1 = new String(“Hello”);
String str2 = new String(“Hello”);
Both of these refers to different String object, and another object gets created for str2

Below is an example showing the same


public class Stringnew {
public static void main(String args[])
{
	String str_a = "Hello";
	String str_b = "Hello";

	String str1 = new String("Hello");
	String str2 = new String("Hello");

	if(str_a==str_b)//== checks address location
	{
		System.out.println("if(str_a==str_b)");
	}
	else
	{
		System.out.println("else (str_a==str_b)");
	}

	if(str_a.equals(str_b))//equals() checks content
	{
		System.out.println("if str_a.equals(str_b)");
	}
	else
	{
		System.out.println("else str_a.equals(str_b)");
	}

	if(str1==str2)//== checks address location
	{
		System.out.println("if str1.equals(str2)");
	}
	else
	{
		System.out.println("else (str_a==str_b)");
	}

	if(str1.equals(str2))//equals() checks content
	{
		System.out.println("if str1.equals(str2)");
	}
	else
	{
		System.out.println("else str1.equals(str2)");
	}
}
}

Output:
if(str_a==str_b)
if str_a.equals(str_b)
else (str_a==str_b)
if str1.equals(str2)

You may also like to read:
Difference between == and equals()
Can String be inherited?
How to override toString()