How To Send HTTP Request GET/POST In Java

A brief Introduction

 

Client server architecture requires two parts as main resources:

  1. Client and
  2. Server

In this client server architecture, A client “requests” or “asks” the server and the server “serves” or “answers” the request.

For example, I enter “www.google.com” in my browser and press “enter”. What is happening is that I am requesting the google server to “serve” me by showing me the search page.

In this case, I am the client and GOOGLE is the server which gives me the google search page having that search bar thingy 🙂

Now, a request can be of two types:

  1. GET and
  2. POST

The difference between both is beyond the scope of this article, and as you can see, despite trying, my “Brief Introduction” is already getting longer, isn’t it ?

In this article, we will show you two examples to make HTTP GET/POST request via following APIs:

  1. Standard HttpURLConnection
  2. Apache HttpClient library (Discussed here)

 

Java HttpURLConnection example

 

This example uses HttpURLConnection (http) and HttpsURLConnection (https) to

  1. Send an HTTP GET request to Google.com to get the search result.
  2. Send an HTTP POST request to Apple.com search form to check the product detail.

HttpURLConnectionExample.java

package com.mudassirshahzad;

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

import javax.net.ssl.HttpsURLConnection;

public class HttpURLConnectionExample {

	private final String USER_AGENT = "Mozilla/5.0";

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

		HttpURLConnectionExample http = new HttpURLConnectionExample();

		System.out.println("Testing 1 - Send Http GET request");
		http.sendGet();

		System.out.println("\nTesting 2 - Send Http POST request");
		http.sendPost();

	}

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

		String url = "http://www.google.com/search?q=mkyong";

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

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

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

		int responseCode = con.getResponseCode();
		System.out.println("\nSending '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
	private void sendPost() throws Exception {

		String url = "https://selfsolve.apple.com/wcResults.do";
		URL obj = new URL(url);
		HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

		//add reuqest header
		con.setRequestMethod("POST");
		con.setRequestProperty("User-Agent", USER_AGENT);
		con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

		String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";

		// Send post request
		con.setDoOutput(true);
		DataOutputStream wr = new DataOutputStream(con.getOutputStream());
		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);
		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());

	}

}

Output

Sending ‘GET’ request to URL : http://www.google.com/search?q=mkyong
Response Code : 200
Google search result…

Testing 2 – Send Http POST request

Sending ‘POST’ request to URL : https://selfsolve.a`pple.com/wcResults.do
Post parameters : sn=C02G8416DRJM&cn=&locale=&caller=&num=12345
Response Code : 200
Apple product detail…

An example using Apache HttpClient library is discussed here

 

 

References

  1. MkYong article

3 thoughts on “How To Send HTTP Request GET/POST In Java”

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top