Java HttpURLConnection Example – Java HTTP Request GET, POST

Filed Under: Java
Java HttpURLConnection

HttpURLConnection class from 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

Java HTTP GET Request for Login Page

Java HTTP POST Request

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.

  • https://localhost:9090/SpringMVCExample/
  • https://localhost:9090/SpringMVCExample/login

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.

  • https://localhost:9090/SpringMVCExample?userName=Pankaj
  • https://localhost:9090/SpringMVCExample/login?userName=Pankaj&pwd=apple123 – for multiple params

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" "">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Page</title>
<form action="home" method="post">
<input type="text" name="userName"><br>
<input type="submit" value="Login">

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. code:

package com.journaldev.utils;


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 {

		System.out.println("GET DONE");
		System.out.println("POST DONE");

	private static void sendGET() throws IOException {
		URL obj = new URL(GET_URL);
		HttpURLConnection con = (HttpURLConnection) obj.openConnection();
		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(
			String inputLine;
			StringBuffer response = new StringBuffer();

			while ((inputLine = in.readLine()) != null) {

			// print result
		} 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.setRequestProperty("User-Agent", USER_AGENT);

		// For POST only - START
		OutputStream os = con.getOutputStream();
		// 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(
			String inputLine;
			StringBuffer response = new StringBuffer();

			while ((inputLine = in.readLine()) != null) {

			// print result
		} 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>
POST Response Code :: 200
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" ""><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>

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 instead of Rest all the steps will be same as above, HttpsURLConnection will take care of SSL handshake and encryption.


  1. Harish says:

    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 ?

  2. Julian says:

    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: 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.

  3. Lakshmi Hari says:

    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(“”);//your url i.e fetch data from .
    SOAPHttpsURLConnection conn = (SOAPHttpsURLConnection) url.openConnection();
    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);
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    String output = “{ “;
    output = output + “\””+”OperationName”+”\”:” + “\”” + “importBulkData” + “\”,”;
    output = output + “\””+”ContentType”+”\”:” + “\”” + “zip” + “\”,”;
    output = output + “\””+”FileName”+”\”:” + “\”” + “” + “\”,”;
    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);
    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), “UTF-8”));
    while ((responseLine = br.readLine()) != null) {
    System.out.println(“… “+ responseLine + ” …. “);

    } 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.


    1. Pankaj says:

      It looks like an encoded response.

  4. Prem C says:

    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.setRequestProperty(“Content-Type”, “text/plain”);
    con.setRequestProperty(strHeaderKey, strHeaderValue);

    os = con.getOutputStream();

    int responseCode = con.getResponseCode();
    in = new BufferedReader(
    new InputStreamReader(con.getErrorStream()));

    in = new BufferedReader(
    new InputStreamReader(con.getInputStream()));

    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null)
    logger.error(“Error Response Code from webservice is “+responseCode+” Response: “+response.toString());
    {” SUCCESSFUL response from web service: “+response.toString());

    1. Raj says:

      Hi Pankaj, Can you please advise on above issue.

  5. Paddy says:

    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.

  6. Neha says:

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

  7. Ramya says:

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

  8. seema says:

    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.setRequestProperty(“Content-Type”, “application/json”);
    urlConnection.setRequestProperty(“Accept”, “application/json”);

    OutputStream wr = urlConnection.getOutputStream();
    System.out.println(“response code from server” + urlConnection.getResponseCode());
    return urlConnection.getResponseCode();

    } catch (Exception e) {
    return 500;
    }finally {


  9. Teena says:

    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

  10. Krishnan says:

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

    1. gaurav singh dhapola says:

      hii krishnan have you solved you program??

  11. LAKATAN Adebayo G. Wilfried says:

    When i send the request using the string directInput, it’s working fine. Unfortunately when i used the json object converted into string jsonInput i got 404 error code. the directInput and jsonInput return the same values

    Someone could please help troubleshooting ? Thanks

    public class Test {

    public static void main(String[] args) {

    try {

    String userCredentials = “USR28:YG739G5XFVPYYV4ADJVW”;

    String basicAuth = “Basic ” + new String(Base64.getEncoder().encode(userCredentials.getBytes()));

    URL url = new URL(“”);

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();


    conn.setRequestProperty(“Content-Type”, “application/json;”);

    conn.setRequestProperty(“Accept”, “application/json”);


    conn.setRequestProperty (“Authorization”, basicAuth);

    //String directInput = “{\”msisdn\”:\”22997858711\”,\”amount\”:1400,\”transref\”:\”QOVNPVTRATYCBK8VIL1A\”,\”clientid\”:\”UBHQ\”}”;

    DepositObject d = new DepositObject();





    Gson gson = new Gson();

    String jsonInput = gson.toJson(d).toString();

    OutputStream os = conn.getOutputStream();



    if (conn.getResponseCode() != 200) {

    throw new RuntimeException(“Failed : HTTP error code : ” + conn.getResponseCode());


    BufferedReader br = new BufferedReader(new InputStreamReader( (conn.getInputStream())));

    String output;

    while ((output = br.readLine()) != null) {




    } catch (MalformedURLException e) {


    } catch (IOException e) {




  12. ADAM says:

    You have missed the con.disconnect() after each call.

    Small things can create HUGE issues in the long run.

  13. Maureen Shaw says:

    This article was very helpful but I am stuck getting a failure back from my request. This works in postman but when trying in java, it fails every way I try it. Sample code below along with the response I get. Any help is very appreciated!!

    //print out the encoded values
    data.addToLog( “sha256hex: “, sha256hex);
    data.addToLog( “xauth: “, xauth);
    StringBuilder sb = new StringBuilder();
    String baseurl = “https://” + apihost + endpoint + “?personID=” + personid;
    data.addToLog( “BaseURL: “, baseurl);

    //print out the JSON search request
    try {
    URL myurl = new URL(null, baseurl , new );
    HttpsURLConnection con = (HttpsURLConnection )myurl.openConnection();
    con.setSSLSocketFactory(new TSLSocketConnectionFactory());
    con.setRequestProperty(“X-Timestamp”, tsparam);
    con.setRequestProperty(“X-Nonce”, nonce64);
    con.setRequestProperty(“X-Authorization”, xauth);
    con.setRequestProperty(“X-Test-Insecure”, “true”);
    con.setRequestProperty(“Content-Type”, “application/json;charset=utf-8”);

    int responseCode = con.getResponseCode();
    data.addToLog(“Response Code= “, con.getResponseCode() +”: “+ con.getResponseMessage());

    if (responseCode == HttpURLConnection.HTTP_OK) { // success
    BufferedReader in = new BufferedReader(new InputStreamReader(
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {

    // print result
    data.addToLog(“Response:”, response.toString() );


    Log results:

    PersonDetailsLookup,custom,Response Code= ,200: OK
    PersonDetailsLookup,custom,Response:,{“serviceModel”:{“errorCode”:{“description”:”Unexpected System Error””value”:”500″}”errorMessage”:”API Invocation Failure – Unknown Error””severity”:{“description”:”FATAL””value”:”3″}}}

  14. Akshay J. says:

    i m getting exception as
    java.lang.ClassCastException: cannot be cast to

    I am calling Http URL

    1. Pankaj says:

      Please check your import statement, I think you have imported the wrong HttpsURLConnection class. You should import class.

  15. Gaurav Arora says:

    I can’t thank u in words/comments. you deserve more than that, really appreciated. Thanks so much sir

  16. Nikita says:


    I have implemented above code and it works fine.
    but I need to accept the values from xls and passing it one by one.

    so can you please provide the solution for this.

  17. immanual says:

    Hi I’m getting the error Any idea why

    1. Ikwan says:

      You need import;

  18. Anjan says:

    How can a post/get an XML or JSON object using this.

  19. incognito says:

    Very usefull, thanks

  20. dheeraj says:

    its really useful for me thank u so much …

  21. Greshma John says:

    Hi ,

    I am getting the following error for post request
    Exception in thread “main” Unable to tunnel through proxy. Proxy returns “HTTP/1.1 400 Bad Request” .

    I have added extra proxy settings in the sendPOST() method .

  22. Thanks for the informative post! I’m still a newbie when it comes to programming using Java programming language but reading posts like this really helps me understand it even more. Cheers!

  23. Mahadev says:

    Hai, how much it will take to get a response once we hit the url??

  24. Deepak says:

    I am using httpsurlconnection.

    Url: “https://localhost:8443/LoginApp”

    + “/restservice/agentchildservice/getAttributesForIdentity”;

    connection.respose is 200. Its a post call. But the values are not getting fetched , its showing me the login page html content.

    BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
    StringBuilder sb = new StringBuilder();
    String output;
    while ((output = br.readLine()) != null) {

    on printing it will give me the login page html in stringbuilder variable.

    I want to get the values. Can you please suggest.

  25. kiran says:

    Hi Pankaj,

    I have an end point url, and i tried through the SOUP UI using REST its giving expected response.
    Now i need to implement through java code and test wether i am getting expected response.

    can you help on this please. For the first time i am working on web services.
    would like to in detail, will be required any jars in eclipse/project etc.


    1. kiran says:

      I have request xml for this as well. how to include while calling web service.

  26. Samas says:

    Connection exceptioni s coming when I run the java code. Will you please help me to use the code. Is it to run the java code and automatically the code runs?

  27. Vandens says:

    Awesome…. I have changed POST_PARAMS into custom xml data in string and it works!

    Thanks you.

  28. naresh says:

    hi sir..

    GET Response Code :: 200
    Home Hello world! The time on the server is March 6, 2015 9:31:04 PM IST.
    POST Response Code :: 200
    User Home PageHi Pankaj

    how to display in web page sir ….
    every time copy paste in browser cannot possible sir … i mean direct when run the programe out put will be display in web page sir

    same like above pages

    thanks sir

  29. Nidh says:

    Really awesome tutorials so easy to understand. Thanks pankaj.

  30. Mathew Eickmeyer says:

    I have to say I’m new to Java but have worked with C, C++ , python and several other languages. Java was the hardest for me to understand and work with but this little tutorial made it very plain how to use the module the way I wanted. Very Nice Job!

  31. suman says:

    is there any way to get request url from browser console

  32. Andrew says:

    Many thanks – I’ve been puzzling over how to POST from a Spring Controller and your article was a great help.

    Andrew (Sheffield UK)

    1. Pankaj says:

      Thanks Andrew, I hope you will find my other articles useful too. 馃檪

    2. naresh says:

      can you give your mail id

  33. KIRAN says:

    hello am getting error : Remote host closed connection during handshake.

    I did same as above except for https connection.

    please help.

    1. Pankaj says:

      Did you used
  34. Rinaldes Duma says:

    Thanks 馃榾

    1. Pankaj says:

      you are welcome.

  35. mbrean says:

    This tutorial is great and clear. But how about 2 parameters?

    1. Mostafa Anter Sayd says:

      String params = “name=mostafa&age=22”;
      u r welcome

      1. Pankaj says:

        Thanks for answering the question Mostafa.

  36. akshay says:

    Nice tutorial.

    Well I didn’t get on thing.


    How can I print my complete POST URL, after adding parameters. Is that possible to output the URL?

    1. Pankaj says:

      POST parameters are not part of URL, so you see them in URL or print them.

  37. Gurgen says:

    Thanks man! This really worked as expected. Good job (y)

    1. Pankaj says:

      You are welcome Gurgen.

  38. abhineet says:

    Hi, I wast tried to hit an end point which is get to fetch the detail using apache http, the json response that I get has got some attributes which are empty array. But the same end point I hit thru a browser or a rest client I don’t see these attributes as part of json response. Why is that ?

    1. Pankaj says:

      It may be because the browser/rest client is not displaying them. Can you try through Chrome Postman or similar kind of tool and check the raw response?
      You can also print the response at the server side before sending it to confirm this.

Comments are closed.

Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors