// Tutorial //

Java HttpURLConnection Example - Java HTTP Request GET, POST

Published on August 3, 2022
Default avatar
By Pankaj
Developer and author at DigitalOcean.
Java HttpURLConnection Example - Java HTTP Request GET, POST

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

HttpURLConnection class from java.net package can be used to send Java HTTP Request programmatically. Today we will learn how to use HttpURLConnection in java program to send GET and POST requests and then print the response.

Java HTTP Request

For our HttpURLConnection example, I am using sample project from Spring MVC Tutorial because it has URLs for GET and POST HTTP methods. Below are the images for this web application, I have deployed it on my localhost tomcat server. Java HTTP GET Request Spring-MVC-HelloWorld Java HTTP GET Request for Login Page Spring-MVC-HelloWorld-GET Java HTTP POST Request Spring-MVC-HelloWorld-POST For Java HTTP GET requests, we have all the information in the browser URL itself. So from the above images, we know that we have the following GET request URLs.

Above URL’s don’t have any parameters but as we know that in HTTP GET requests parameters are part of URL itself, so for example if we have to send a parameter named userName with value as Pankaj then the URLs would have been like below.

If we know the POST URL and what parameters it’s expecting, it’s awesome but in this case, we will figure it out from the login form source. Below is the HTML code we get when we view the source of the login page in any of the browsers.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Page</title>
</head>
<body>
<form action="home" method="post">
<input type="text" name="userName"><br>
<input type="submit" value="Login">
</form>
</body>
</html>

Look at the form method in the source, as expected it’s POST method. Now see that action is “home”, so the POST URL would be https://localhost:9090/SpringMVCExample/home. Now check the different elements in the form, from the above form we can deduce that we need to send one POST parameter with name userName and it’s of type String. So now we have complete details of the GET and POST requests and we can proceed for the Java HTTP Request example program. Below are the steps we need to follow for sending Java HTTP requests using HttpURLConnection class.

  1. Create URL object from the GET/POST URL String.
  2. Call openConnection() method on URL object that returns instance of HttpURLConnection
  3. Set the request method in HttpURLConnection instance, default value is GET.
  4. Call setRequestProperty() method on HttpURLConnection instance to set request header values, such as “User-Agent” and “Accept-Language” etc.
  5. We can call getResponseCode() to get the response HTTP code. This way we know if the request was processed successfully or there was any HTTP error message thrown.
  6. For GET, we can simply use Reader and InputStream to read the response and process it accordingly.
  7. For POST, before we read response we need to get the OutputStream from HttpURLConnection instance and write POST parameters into it.

HttpURLConnection Example

Based on the above steps, below is the example program showing usage of HttpURLConnection to send Java GET and POST requests. HttpURLConnectionExample.java code:

package com.journaldev.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpURLConnectionExample {

	private static final String USER_AGENT = "Mozilla/5.0";

	private static final String GET_URL = "https://localhost:9090/SpringMVCExample";

	private static final String POST_URL = "https://localhost:9090/SpringMVCExample/home";

	private static final String POST_PARAMS = "userName=Pankaj";

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

		sendGET();
		System.out.println("GET DONE");
		sendPOST();
		System.out.println("POST DONE");
	}

	private static void sendGET() throws IOException {
		URL obj = new URL(GET_URL);
		HttpURLConnection con = (HttpURLConnection) obj.openConnection();
		con.setRequestMethod("GET");
		con.setRequestProperty("User-Agent", USER_AGENT);
		int responseCode = con.getResponseCode();
		System.out.println("GET Response Code :: " + responseCode);
		if (responseCode == HttpURLConnection.HTTP_OK) { // success
			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());
		} else {
			System.out.println("GET request not worked");
		}

	}

	private static void sendPOST() throws IOException {
		URL obj = new URL(POST_URL);
		HttpURLConnection con = (HttpURLConnection) obj.openConnection();
		con.setRequestMethod("POST");
		con.setRequestProperty("User-Agent", USER_AGENT);

		// For POST only - START
		con.setDoOutput(true);
		OutputStream os = con.getOutputStream();
		os.write(POST_PARAMS.getBytes());
		os.flush();
		os.close();
		// For POST only - END

		int responseCode = con.getResponseCode();
		System.out.println("POST Response Code :: " + responseCode);

		if (responseCode == HttpURLConnection.HTTP_OK) { //success
			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());
		} else {
			System.out.println("POST request not worked");
		}
	}

}

When we execute the above program, we get below response.

GET Response Code :: 200
<html><head>	<title>Home</title></head><body><h1>	Hello world!  </h1><P>  The time on the server is March 6, 2015 9:31:04 PM IST. </P></body></html>
GET DONE
POST Response Code :: 200
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>User Home Page</title></head><body><h3>Hi Pankaj</h3></body></html>
POST DONE

Just compare it with the browser HTTP response and you will see that it’s same. You can also save response into any HTML file and open it to compare the responses visually. Quick Tip: If you have to send GET/POST requests over HTTPS protocol, then all you need is to use javax.net.ssl.HttpsURLConnection instead of java.net.HttpURLConnection. Rest all the steps will be same as above, HttpsURLConnection will take care of SSL handshake and encryption.


Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

Sign up
About the authors
Default avatar
Pankaj

author

Developer and author at DigitalOcean.

Still looking for an answer?

Was this helpful?

HttpURLConnection sets “connection: keep-alive” by default for every request. I have written a HTTP server and I am keeping the TCP connection open as request header contains keep-alive. But when sending second request, HttpURLConnection is opening new TCP connection. Shouldn’t it use first TCP connection itself. I have tried closing input stream and disconnecting HttpURLConnection instance, but still HttpURLConnection instance always opens a new TCP connection. I have even tried setting property “http.maxConnections” to “1”. Is there any way in android to send multiple HTTP requests on a single persistent TCP connection ?

- Harish

    Hi Pankaj, thank you so much for the post. I have an issue. When i’m trying to do a POST, i do : HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); But when it try to do : OutputStream os = con.getOutputStream(); This happened: javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure Is weird because when i did a POST to a google service it worked well, but with other API has this exception. Thak you for your help.

    - Julian

      Hi Pankaj, I am trying to invoke a REST API. I am getting the proper response when invoked from POSTMAN. But, when I am trying to call from a Java program, I am getting the response in some junk characters. try { URL url = new URL(“https://ucf5-zodx-fa-ext.oracledemos.com/fscmRestApi/resources/11.13.18.05/erpintegrations”);//your url i.e fetch data from . SOAPHttpsURLConnection conn = (SOAPHttpsURLConnection) url.openConnection(); conn.setRequestMethod(“POST”); String authString = “fin_impl” + “:” + “…”; // masked the password for security reasons String encodedAuth = Base64.getEncoder().encodeToString(authString.getBytes()); String authHeader = “Basic " + encodedAuth; conn.setRequestProperty (“Authorization”, authHeader); conn.setRequestProperty(“Content-Type”,“application/json”); conn.setRequestProperty(“Accept”,“application/json”); conn.setRequestProperty(“Accept-Encoding”,“gzip”); conn.setConnectTimeout(5000); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); String output = “{ “; output = output + “\””+“OperationName”+”\”:" + “\”" + “importBulkData” + “\”,“; output = output + “\””+“DocumentContent”+“\”:" + “\”" + “UEsDBBQAAAAIAOeg9FC15oa6wQAAAL0CAAAXAAAAQXBJbnZvaWNlc0ludGVyZmFjZS5jc3bVkF8LgjAUxd+DvoPQ66W2ifZsm5FkFi6fRdqMgU7wT/TxUwMVn6KHoN9l3Hu2cS4cyyTEQh0QcWzsmkppWVVGpFUN7rOWpU4ysMZfNkFo3XaCCNoge4Mw8DpJU6XvBpflQ91kBZhY5njdGrfmrD/78HwyPMrBucQ0KxoRM5kXwK9OwJyQQY+X51KopJbTLTAV9ODSY7dBi6QUsAoi34eRUb+nQRM8zLOXuUVH0NbXuAFbLobg8EfxYtj+dbw/TvcFUEsDBBQAAAAIAOmg9FDbs3GzSgAAAKABAAAbAAAAQXBJbnZvaWNlTGluZXNJbnRlcmZhY2UuY3N2MzU2MjI1AAEdQx3PEFdfHSMDAz0gDx346ego+4X6+ADljQz0Dcz0DQzB4hBBdAAT9dMxhOiFmUFD4OrnwstlCvOPIcw/xkPaPwBQSwMEFAAAAAgA6p70UI3NvI1wAAAAogAAABEAAABBUFRFU1QuUFJPUEVSVElFU8svSkzOSdVPLCgo1k8tLtZPy8xLzEvOTMwp1i9IrExMykkt1s/MK8vPTAYySooS84oTk0sy8/OKdRwDIjw9fQNCgIwQ1+AQHWW/UB8fndBgQwWn0uLMPKBhCqF5mSVQcVyka0VJalFeYg4WKUMIDQBQSwECFAAUAAAACADnoPRQteaGusEAAAC9AgAAFwAAAAAAAAABACAAAAAAAAAAQXBJbnZvaWNlc0ludGVyZmFjZS5jc3ZQSwECFAAUAAAACADpoPRQ27Nxs0oAAACgAQAAGwAAAAAAAAABACAAAAD2AAAAQXBJbnZvaWNlTGluZXNJbnRlcmZhY2UuY3N2UEsBAhQAFAAAAAgA6p70UI3NvI1wAAAAogAAABEAAAAAAAAAAQAgAAAAeQEAAEFQVEVTVC5QUk9QRVJUSUVTUEsFBgAAAAADAAMAzQAAABgCAAAAAA==” + “\”,“; output = output + “\””+“ContentType”+“\”:" + “\”" + “zip” + “\”,“; output = output + “\””+“FileName”+“\”:" + “\”" + “apinvoiceimport.zip” + “\”,“; output = output + “\””+“JobName”+“\”:" + “\”" + “oracle/apps/ess/financials/payables/invoices/transactions,APXIIMPT” + “\”,“; output = output + “\””+“ParameterList”+“\”:" + “\”" + “#NULL,US1 Business Unit,#NULL,#NULL,#NULL,#NULL,#NULL,External,#NULL,#NULL,#NULL,1,#NULL” + “\”“; output = output + " }”; System.out.println(“before writing… " + output); wr.write(output); wr.flush(); BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), “UTF-8”)); while ((responseLine = br.readLine()) != null) { System.out.println(”… "+ responseLine + " … "); response.append(responseLine); } conn.disconnect(); } catch (Exception e) { System.out.println("Exception in NetClientGet:- " + e); } I am getting some junk and non-printable characters in the response. something as below: … ? Please help. Thanks, Hari

      - Lakshmi Hari

        I am getting error while sending below: Response Code: 405 Response: {“Message”:“The requested resource does not support http method ‘POST’.”} My Code: URL obj = new URL(strWebServiceUrl); con = (HttpsURLConnection) obj.openConnection(); //add request header //con.setRequestMethod(“GET”); con.setRequestProperty(“Content-Type”, “text/plain”); con.setRequestProperty(strHeaderKey, strHeaderValue); con.setDoOutput(true); os = con.getOutputStream(); os.flush(); int responseCode = con.getResponseCode(); if(responseCode!=200) { in = new BufferedReader( new InputStreamReader(con.getErrorStream())); } else { in = new BufferedReader( new InputStreamReader(con.getInputStream())); } String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } if(responseCode!=200) { logger.error("Error Response Code from webservice is “+responseCode+” Response: “+response.toString()); System.out.println(response.toString()); } else { logger.info(” SUCCESSFUL response from web service: "+response.toString()); System.out.println(response.toString()); }

        - Prem C

          Hi , I am using Post method to send JSON object through proxy setting and header . Response I am getting 500 Internal server Error ? Please help me. Thx

          - Paddy

            How can i send a request body which contains nested Json for example using java.net.HttpURLConnection:- { “moduleId”: “abc”, “properties”: { “desired”: { “Graphs”: { “PersonDetection”: { “location”: “https://graphexample.yaml”, “version”: 1, “parameters”: {}, “enabled”: true, “status”: “started” } } } }

            - Neha

              Hello I have to send a GET request with parameter and get Json response from third party using API key. Kindly help.

              - Ramya

                here is my function below : , connection is made successfully because i receive response 200 but it send blank data to the POST request. hence my POST request makes entry to db with all fields blank except id i.e. which I am generating on POST request on server side. Note : when I capture the url and json string on debug mode , and send same through POSTMAN , data gets created successfully at DB and i receive 200. I am clueless now, how to debug the issue public static int POST(String urlstr, String jsonbody) { URL url = null; HttpURLConnection urlConnection = null; String result = “”; try { url = new URL(urlstr); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setConnectTimeout(5000); urlConnection.setRequestProperty(“Content-Type”, “application/json”); urlConnection.setRequestProperty(“Accept”, “application/json”); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setRequestMethod(“POST”); OutputStream wr = urlConnection.getOutputStream(); wr.write(jsonbody.getBytes()); wr.flush(); wr.close(); System.out.println(“response code from server” + urlConnection.getResponseCode()); return urlConnection.getResponseCode(); } catch (Exception e) { e.printStackTrace(); return 500; }finally { urlConnection.disconnect(); } }

                - seema

                  Hi Pankaj, I have one small required with this HTTP post connection, in postman I am using post method to pass a url and content from body section choosing raw option. I am able to open the connection but not sure how to post this body content in post call. can you please advise. Thanks in advance

                  - Teena

                    Hai I have to develop a program for get and post request can you help me for that.

                    - Krishnan