How to send HTTP request GET/POST in Java

http logo

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.

1. 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.mkyong;

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("\nSending '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.apple.com/wcResults.do
Post parameters : sn=C02G8416DRJM&cn=&locale=&caller=&num=12345
Response Code : 200
Apple product detail...

2. Apache HttpClient

This is the equivalent example, but using Apache HttpClient to make HTTP GET/POST request.

HttpClientExample.java

package com.mkyong;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class HttpClientExample {

	private final String USER_AGENT = "Mozilla/5.0";

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

		HttpClientExample http = new HttpClientExample();

		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=developer";

		HttpClient client = new DefaultHttpClient();
		HttpGet request = new HttpGet(url);

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

		HttpResponse response = client.execute(request);

		System.out.println("\nSending 'GET' request to URL : " + url);
		System.out.println("Response Code : " + 
                       response.getStatusLine().getStatusCode());

		BufferedReader rd = new BufferedReader(
                       new InputStreamReader(response.getEntity().getContent()));

		StringBuffer result = new StringBuffer();
		String line = "";
		while ((line = rd.readLine()) != null) {
			result.append(line);
		}

		System.out.println(result.toString());

	}

	// HTTP POST request
	private void sendPost() throws Exception {

		String url = "https://selfsolve.apple.com/wcResults.do";

		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(url);

		// add header
		post.setHeader("User-Agent", USER_AGENT);

		List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
		urlParameters.add(new BasicNameValuePair("sn", "C02G8416DRJM"));
		urlParameters.add(new BasicNameValuePair("cn", ""));
		urlParameters.add(new BasicNameValuePair("locale", ""));
		urlParameters.add(new BasicNameValuePair("caller", ""));
		urlParameters.add(new BasicNameValuePair("num", "12345"));

		post.setEntity(new UrlEncodedFormEntity(urlParameters));

		HttpResponse response = client.execute(post);
		System.out.println("\nSending 'POST' request to URL : " + url);
		System.out.println("Post parameters : " + post.getEntity());
		System.out.println("Response Code : " + 
                                    response.getStatusLine().getStatusCode());

		BufferedReader rd = new BufferedReader(
                        new InputStreamReader(response.getEntity().getContent()));

		StringBuffer result = new StringBuffer();
		String line = "";
		while ((line = rd.readLine()) != null) {
			result.append(line);
		}

		System.out.println(result.toString());

	}

}

References

  1. Apache HttpClient
  2. Apache HttpClient examples
  3. Automate login a website with Java HttpsURLConnection

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
IchHabsDrauf
Guest
IchHabsDrauf

I just copied the post method u’ve created and wanted to use it somewhere the same way as you did. It is just like your class but without the get() thing

when I run it on one site of mine i get:

java.lang.ClassCastException: sun.net.www.protocol.http.HttpURLConnection cannot be cast to javax.net.ssl.HttpsURLConnection
at tests.web.POSTRequestTest.sendPost(POSTRequestTest.java:32)
at tests.web.POSTRequestTest.main(POSTRequestTest.java:18)

ahemad
Guest
ahemad

how to post a JSON data to server(tomcat7) using POSTmethod

leonskb4
Guest
leonskb4

replace the next lines

List urlParameters = new ArrayList();
urlParameters.add(new BasicNameValuePair(“sn”, “C02G8416DRJM”));
urlParameters.add(new BasicNameValuePair(“cn”, “”));
urlParameters.add(new BasicNameValuePair(“locale”, “”));
urlParameters.add(new BasicNameValuePair(“caller”, “”));
urlParameters.add(new BasicNameValuePair(“num”, “12345”));

post.setEntity(new UrlEncodedFormEntity(urlParameters));

with

post.setEntity(new StringEntity(“{“sn”:”C02G8416DRJM”}”,ContentType.create(“application/json”)));

Daniel
Guest
Daniel

Maybe consider using a StringBuilder instead of the StringBuffer?

Samir
Guest
Samir

Hi ,
After implementation i got below security related bug.

The call to HttpHost() (in my class on line 113 )uses an unencrypted protocol instead of an encrypted protocol to communicate with the server.

code:
private HttpHost getHttpProxy(String proxyHost,int proxyPort) {
return new HttpHost(proxyHost, proxyPort);
}

so how can i encrypt it?

Paul
Guest
Paul

Hi,
Thank you for these useful examples!

When I used the Java Post example, I’ve encountered some issues when sending content than contains non English characters.

Investigating it showed that the cause is the usage of DataOutputStream.writeBytes(). From this class documentation: “Each character in the string is written out, in sequence, by discarding its high eight bits.”

The solution is to use:
Writer out = new BufferedWriter(new OutputStreamWriter(con.getOutputStream()));
out.write(urlParameters);

MMU UNI
Guest
MMU UNI

yeah thanks mkyong can already
for those cannot just change this line
HttpClientExample http = new HttpClientExample();

MMU UNI
Guest
MMU UNI

HI mkyong why i have this error ?
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Exception in thread “main” java.lang.RuntimeException: Uncompilable source code – cannot find symbol
symbol: class HttpURLConnectionExample
location: class lab1.Lab1
at lab1.Lab1.main(Lab1.java:27)
Java Result: 1
BUILD SUCCESSFUL (total time: 2 seconds)
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

Curtis Newton
Guest
Curtis Newton

learn how to write java programs first maybe

Utkarsh
Guest
Utkarsh

Post parameters : org.apache.http.client.entity.UrlEncodedFormEntity@548ad73b
Response Code : 302
302 FoundFoundThe document has moved here.

Ta grand mère
Guest
Ta grand mère

For Java HttpURLConnection example you use no try/catch. A developer who uses no try/catch should be buried alive

Nicolas Caballero
Guest
Nicolas Caballero

Hi, i am getting this exception when i try to open connection

Info: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

I can not understand why open this connection requires a certificate. This is related with the agent used (mozilla)?

kevin
Guest
kevin

nice website

RahulS
Guest
RahulS

very helpfull Thanks !!

Guest
Guest
Guest

could you also tell how to sen request body for a port call

Andreew
Guest
Andreew

Dude, this was a god send.

Yanko
Guest
Yanko

how about 3. Using Java Socket?

Sandeep Shukla
Guest
Sandeep Shukla

Hi,
I have a java standalone server which listen the request and then I open a socket connection. My requirement is, how can I know weather java client is using http or https protocol in my server programe.

Luc
Guest
Luc

What means this line of code?
String urlParameters = “sn=C02G8416DRJM&cn=&locale=&caller=&num=12345”;

Martin
Guest
Martin

Thank for Sharing this post with us. Very Helpfull and usefull Information. Hope you keep it up in future also by providing informative post.This Post is very much handy.Best of Luck & Cheers.
Thank You

David
Guest
David

Thank You for giving us idea about how to send HTTP request GET/POST in Java.
Thank You Very Much For Sharing Your Knowledge with US.Now a Day No Body Do what you did.We are really blessed with this types of informatic Posting. Hope you continue this in Future.Keep us updated with this this types of blogs.Best of Luck & Cheers.
Thanks David

Robert Lecomte
Guest
Robert Lecomte

very helpfull Thanks !!

John
Guest
John

Thank you very very much <3

Yonko
Guest
Yonko

I dont understand the method for the http connection example could someone please explain it using an example . you know one with an actual url and parameters and api call

Jesus David Sanchez Suarez
Guest
Jesus David Sanchez Suarez

Hi all
The example with HttpURLConnection does not work, I have been looking for a solution but I have not found my error is this:
java.net.ConnectException: Connection refused: connect…
The server is active, port 8000 is active, it is in a local environment

Nilupul Nuwan
Guest
Nilupul Nuwan

this perfectly working. but when i use java Swing i can’t pass the parameters to urlParameters from jTextField.

CODE:
String urlParameters = “NAME=”+jTextField_name.getText()+”&address=”+jTextField_add.getText();

OUTPUT:
Post parameters :NAME=&address=

also i assign “jTextField_name.getText()” to variable but output was same.

so can you solved this problem

Curtis Newton
Guest
Curtis Newton

“unable to find valid certification path to requested target”

Mike
Guest
Mike

This error is not a problem with the code sample given above but it means that the server that you are attempting to connect to is secured with a certificate. You will need to add that severs certificate to your local keystore.

Byron
Guest
Byron

Really Awesome! Thank you so much Really helped!

Danio
Guest
Danio

Can you describe not how to send but how to recieve POST or GET request? I would like to recieve POST for example, but without using servlets. I would rather use JQuery and send POST to .jar file. Can it be done?

ironhide
Guest
ironhide

publishing the article is ok. how come the same work for you and not for others.

Dave
Guest
Dave

Does mkyong ever respond to questions or posts..?

Madhuri Kalshetty
Guest
Madhuri Kalshetty

HttpUrlConnection is synchronous or asynchronous