Tutorial

How To Use Java HttpURLConnection for HTTP GET and POST Requests

Updated on November 19, 2022
authorauthor

Pankaj and Bradley Kouchi

How To Use Java HttpURLConnection for HTTP GET and POST Requests

Introduction

The HttpURLConnection class from java.net package can be used to send a Java HTTP Request programmatically. In this article, you will learn how to use HttpURLConnection in a Java program to send GET and POST requests and then print the response.

Prerequisites

For this HttpURLConnection example, you should have completed the Spring MVC Tutorial because it has URLs for GET and POST HTTP methods.

Consider deploying to a localhost Tomcat server.

SpringMVCExample Summary

Java HTTP GET Request

  • localhost:8080/SpringMVCExample/

Spring-MVC-HelloWorld

Java HTTP GET Request for Login Page

  • localhost:8080/SpringMVCExample/login

Spring-MVC-HelloWorld-GET

Java HTTP POST Request

  • localhost:8080/SpringMVCExample?userName=Pankaj
  • localhost:8080/SpringMVCExample/login?userName=Pankaj&pwd=apple123 - for multiple params

Spring-MVC-HelloWorld-POST

Deriving parameters from the form

The HTML of the login page contains the following form:

<!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>
  • The method is POST.
  • The action is home.
    • localhost:8080/SpringMVCExample/home
  • userName is of type text.

You can construct a POST request to:

localhost:8080/SpringMVCExample/home?userName=Pankaj

This will serve as the basis for the HttpURLConnection example.

HttpURLConnection Example

Here are the steps for sending Java HTTP requests using HttpURLConnection class:

  1. Create a URL object from the GET or POST URL String.
  2. Call the openConnection() method on the URL object that returns an 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", "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 if there was any HTTP error message thrown.
  6. For GET, use Reader and InputStream to read the response and process it accordingly.
  7. For POST, before the code handles the response, it needs to get the OutputStream from the HttpURLConnection instance and write POST parameters into it.

Here is an example program that uses HttpURLConnection to send Java GET and POST requests:

HttpURLConnectionExample.java
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 did not work.");
		}

	}

	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 did not work.");
		}
	}

}

Compile and run the code. It will produce the following output:

Output
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

Compare this output to the browser HTTP response.

If you have to send GET and POST requests over HTTPS protocol, then you need to use javax.net.ssl.HttpsURLConnection instead of java.net.HttpURLConnection. HttpsURLConnection will handle the SSL handshake and encryption.

Conclusion

In this article, you learned how to use HttpURLConnection in a Java program to send GET and POST requests and then print the response.

Continue your learning with more Java tutorials.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Category:
Tutorial
Tags:

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
July 6, 2015

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 ?

- abhineet

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
May 28, 2016

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.

- Pankaj

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    September 25, 2015

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

    - Gurgen

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    May 28, 2016

    You are welcome Gurgen.

    - Pankaj

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      November 29, 2015

      Nice tutorial. Well I didn’t get on thing. `os.write(POST_PARAMS.getBytes()); os.flush(); os.close();` How can I print my complete POST URL, after adding parameters. Is that possible to output the URL?

      - akshay

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      May 28, 2016

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

      - Pankaj

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        December 8, 2015

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

        - mbrean

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        February 27, 2016

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

        - Mostafa Anter Sayd

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        May 28, 2016

        Thanks for answering the question Mostafa.

        - Pankaj

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          December 16, 2015

          Thanks :D

          - Rinaldes Duma

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          May 28, 2016

          you are welcome.

          - Pankaj

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            February 16, 2016

            hello am getting error : javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake. I did same as above except for https connection. please help.

            - KIRAN

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            May 28, 2016

            Did you used

             javax.net.ssl.HttpsURLConnection
            

            - Pankaj

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              April 4, 2016

              Many thanks - I’ve been puzzling over how to POST from a Spring Controller and your article was a great help. Andrew (Sheffield UK)

              - Andrew

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              May 28, 2016

              Thanks Andrew, I hope you will find my other articles useful too. :)

              - Pankaj

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                January 2, 2017

                can you give your mail id

                - naresh

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  June 7, 2016

                  is there any way to get request url from browser console

                  - suman

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    June 23, 2016

                    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 java.net module the way I wanted. Very Nice Job!

                    - Mathew Eickmeyer

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      November 8, 2016

                      Really awesome tutorials so easy to understand. Thanks pankaj.

                      - Nidh

                        JournalDev
                        DigitalOcean Employee
                        DigitalOcean Employee badge
                        December 5, 2016

                        hi sir… output:: GET Response Code :: 200 Home Hello world! The time on the server is March 6, 2015 9:31:04 PM IST. GET DONE POST Response Code :: 200 User Home PageHi Pankaj POST DONE 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

                        - naresh

                          JournalDev
                          DigitalOcean Employee
                          DigitalOcean Employee badge
                          January 11, 2017

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

                          - Vandens

                            JournalDev
                            DigitalOcean Employee
                            DigitalOcean Employee badge
                            February 8, 2017

                            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?

                            - Samas

                              JournalDev
                              DigitalOcean Employee
                              DigitalOcean Employee badge
                              May 4, 2017

                              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. Thanks, Kiran

                              - kiran

                              JournalDev
                              DigitalOcean Employee
                              DigitalOcean Employee badge
                              May 4, 2017

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

                              - kiran

                                JournalDev
                                DigitalOcean Employee
                                DigitalOcean Employee badge
                                May 18, 2017

                                Hi 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) { sb.append(output); } System.out.println(sb); on printing it will give me the login page html in stringbuilder variable. I want to get the values. Can you please suggest.

                                - Deepak

                                  JournalDev
                                  DigitalOcean Employee
                                  DigitalOcean Employee badge
                                  June 3, 2017

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

                                  - Mahadev

                                    JournalDev
                                    DigitalOcean Employee
                                    DigitalOcean Employee badge
                                    July 21, 2017

                                    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!

                                    - Kristina Mendoza

                                      JournalDev
                                      DigitalOcean Employee
                                      DigitalOcean Employee badge
                                      August 17, 2017

                                      Hi , I am getting the following error for post request Exception in thread “main” java.io.IOException: Unable to tunnel through proxy. Proxy returns “HTTP/1.1 400 Bad Request” . I have added extra proxy settings in the sendPOST() method .

                                      - Greshma John

                                        JournalDev
                                        DigitalOcean Employee
                                        DigitalOcean Employee badge
                                        September 26, 2017

                                        its really useful for me thank u so much …

                                        - dheeraj

                                          JournalDev
                                          DigitalOcean Employee
                                          DigitalOcean Employee badge
                                          October 31, 2017

                                          Very usefull, thanks

                                          - incognito

                                            JournalDev
                                            DigitalOcean Employee
                                            DigitalOcean Employee badge
                                            January 22, 2018

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

                                            - Anjan

                                              JournalDev
                                              DigitalOcean Employee
                                              DigitalOcean Employee badge
                                              February 12, 2018

                                              Hi I’m getting the error java.net.UnknownHostException: Any idea why

                                              - immanual

                                              JournalDev
                                              DigitalOcean Employee
                                              DigitalOcean Employee badge
                                              April 25, 2018

                                              You need import java.net.UnknownHostException;

                                              - Ikwan

                                                JournalDev
                                                DigitalOcean Employee
                                                DigitalOcean Employee badge
                                                August 7, 2018

                                                Hi, 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.

                                                - Nikita

                                                  JournalDev
                                                  DigitalOcean Employee
                                                  DigitalOcean Employee badge
                                                  January 19, 2019

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

                                                  - Gaurav Arora

                                                    JournalDev
                                                    DigitalOcean Employee
                                                    DigitalOcean Employee badge
                                                    January 28, 2019

                                                    i m getting exception as java.lang.ClassCastException: sun.net.www.protocol.http.HttpURLConnection cannot be cast to javax.net.ssl.HttpsURLConnection. I am calling Http URL

                                                    - Akshay J.

                                                    JournalDev
                                                    DigitalOcean Employee
                                                    DigitalOcean Employee badge
                                                    January 28, 2019

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

                                                    - Pankaj

                                                      JournalDev
                                                      DigitalOcean Employee
                                                      DigitalOcean Employee badge
                                                      February 21, 2019

                                                      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 sun.net.www.protocol.https.Handler() ); 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.setRequestMethod(method); con.setDoOutput(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( 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()); 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”}}}

                                                      - Maureen Shaw

                                                        JournalDev
                                                        DigitalOcean Employee
                                                        DigitalOcean Employee badge
                                                        March 25, 2019

                                                        You have missed the con.disconnect() after each call. Small things can create HUGE issues in the long run.

                                                        - ADAM

                                                          JournalDev
                                                          DigitalOcean Employee
                                                          DigitalOcean Employee badge
                                                          June 19, 2019

                                                          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(“https://74.208.84.251:8221/QosicBridge/user/deposit”); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(“POST”); conn.setRequestProperty(“Content-Type”, “application/json;”); conn.setRequestProperty(“Accept”, “application/json”); conn.setDoOutput(true); conn.setRequestProperty (“Authorization”, basicAuth); //String directInput = “{\“msisdn\”:\“22997858711\”,\“amount\”:1400,\“transref\”:\“QOVNPVTRATYCBK8VIL1A\”,\“clientid\”:\“UBHQ\”}”; DepositObject d = new DepositObject(); d.setMsisdn(“22997858711”); d.setAmount(35); d.setTransref(“QOVNPVTRATYCBK8VIL1A”); d.setClientid(“UHBQ”); Gson gson = new Gson(); String jsonInput = gson.toJson(d).toString(); OutputStream os = conn.getOutputStream(); os.write(jsonInput.getBytes()); os.flush(); 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) { System.out.println(output); } conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }

                                                          - LAKATAN Adebayo G. Wilfried

                                                            JournalDev
                                                            DigitalOcean Employee
                                                            DigitalOcean Employee badge
                                                            August 19, 2019

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

                                                            - Krishnan

                                                            JournalDev
                                                            DigitalOcean Employee
                                                            DigitalOcean Employee badge
                                                            January 10, 2020

                                                            hii krishnan have you solved you program??

                                                            - gaurav singh dhapola

                                                              JournalDev
                                                              DigitalOcean Employee
                                                              DigitalOcean Employee badge
                                                              September 2, 2019

                                                              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

                                                                JournalDev
                                                                DigitalOcean Employee
                                                                DigitalOcean Employee badge
                                                                January 22, 2018

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

                                                                - Anjan

                                                                  JournalDev
                                                                  DigitalOcean Employee
                                                                  DigitalOcean Employee badge
                                                                  February 12, 2018

                                                                  Hi I’m getting the error java.net.UnknownHostException: Any idea why

                                                                  - immanual

                                                                  JournalDev
                                                                  DigitalOcean Employee
                                                                  DigitalOcean Employee badge
                                                                  April 25, 2018

                                                                  You need import java.net.UnknownHostException;

                                                                  - Ikwan

                                                                    JournalDev
                                                                    DigitalOcean Employee
                                                                    DigitalOcean Employee badge
                                                                    August 7, 2018

                                                                    Hi, 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.

                                                                    - Nikita

                                                                      JournalDev
                                                                      DigitalOcean Employee
                                                                      DigitalOcean Employee badge
                                                                      January 19, 2019

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

                                                                      - Gaurav Arora

                                                                        JournalDev
                                                                        DigitalOcean Employee
                                                                        DigitalOcean Employee badge
                                                                        January 28, 2019

                                                                        i m getting exception as java.lang.ClassCastException: sun.net.www.protocol.http.HttpURLConnection cannot be cast to javax.net.ssl.HttpsURLConnection. I am calling Http URL

                                                                        - Akshay J.

                                                                        JournalDev
                                                                        DigitalOcean Employee
                                                                        DigitalOcean Employee badge
                                                                        January 28, 2019

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

                                                                        - Pankaj

                                                                          JournalDev
                                                                          DigitalOcean Employee
                                                                          DigitalOcean Employee badge
                                                                          February 21, 2019

                                                                          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 sun.net.www.protocol.https.Handler() ); 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.setRequestMethod(method); con.setDoOutput(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( 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()); 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”}}}

                                                                          - Maureen Shaw

                                                                            JournalDev
                                                                            DigitalOcean Employee
                                                                            DigitalOcean Employee badge
                                                                            March 25, 2019

                                                                            You have missed the con.disconnect() after each call. Small things can create HUGE issues in the long run.

                                                                            - ADAM

                                                                              JournalDev
                                                                              DigitalOcean Employee
                                                                              DigitalOcean Employee badge
                                                                              June 19, 2019

                                                                              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(“https://74.208.84.251:8221/QosicBridge/user/deposit”); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(“POST”); conn.setRequestProperty(“Content-Type”, “application/json;”); conn.setRequestProperty(“Accept”, “application/json”); conn.setDoOutput(true); conn.setRequestProperty (“Authorization”, basicAuth); //String directInput = “{\“msisdn\”:\“22997858711\”,\“amount\”:1400,\“transref\”:\“QOVNPVTRATYCBK8VIL1A\”,\“clientid\”:\“UBHQ\”}”; DepositObject d = new DepositObject(); d.setMsisdn(“22997858711”); d.setAmount(35); d.setTransref(“QOVNPVTRATYCBK8VIL1A”); d.setClientid(“UHBQ”); Gson gson = new Gson(); String jsonInput = gson.toJson(d).toString(); OutputStream os = conn.getOutputStream(); os.write(jsonInput.getBytes()); os.flush(); 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) { System.out.println(output); } conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }

                                                                              - LAKATAN Adebayo G. Wilfried

                                                                                JournalDev
                                                                                DigitalOcean Employee
                                                                                DigitalOcean Employee badge
                                                                                August 19, 2019

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

                                                                                - Krishnan

                                                                                JournalDev
                                                                                DigitalOcean Employee
                                                                                DigitalOcean Employee badge
                                                                                January 10, 2020

                                                                                hii krishnan have you solved you program??

                                                                                - gaurav singh dhapola

                                                                                  JournalDev
                                                                                  DigitalOcean Employee
                                                                                  DigitalOcean Employee badge
                                                                                  September 2, 2019

                                                                                  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

                                                                                    JournalDev
                                                                                    DigitalOcean Employee
                                                                                    DigitalOcean Employee badge
                                                                                    February 8, 2020

                                                                                    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

                                                                                      JournalDev
                                                                                      DigitalOcean Employee
                                                                                      DigitalOcean Employee badge
                                                                                      April 29, 2020

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

                                                                                      - Ramya

                                                                                        JournalDev
                                                                                        DigitalOcean Employee
                                                                                        DigitalOcean Employee badge
                                                                                        June 23, 2020

                                                                                        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

                                                                                          JournalDev
                                                                                          DigitalOcean Employee
                                                                                          DigitalOcean Employee badge
                                                                                          June 29, 2020

                                                                                          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

                                                                                            JournalDev
                                                                                            DigitalOcean Employee
                                                                                            DigitalOcean Employee badge
                                                                                            August 19, 2020

                                                                                            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

                                                                                            JournalDev
                                                                                            DigitalOcean Employee
                                                                                            DigitalOcean Employee badge
                                                                                            September 18, 2021

                                                                                            Hi Pankaj, Can you please advise on above issue.

                                                                                            - Raj

                                                                                              JournalDev
                                                                                              DigitalOcean Employee
                                                                                              DigitalOcean Employee badge
                                                                                              September 21, 2020

                                                                                              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

                                                                                              JournalDev
                                                                                              DigitalOcean Employee
                                                                                              DigitalOcean Employee badge
                                                                                              September 22, 2020

                                                                                              It looks like an encoded response.

                                                                                              - Pankaj

                                                                                                JournalDev
                                                                                                DigitalOcean Employee
                                                                                                DigitalOcean Employee badge
                                                                                                February 4, 2021

                                                                                                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

                                                                                                  JournalDev
                                                                                                  DigitalOcean Employee
                                                                                                  DigitalOcean Employee badge
                                                                                                  March 10, 2021

                                                                                                  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

                                                                                                    Try DigitalOcean for free

                                                                                                    Click below to sign up and get $200 of credit to try our products over 60 days!

                                                                                                    Sign up

                                                                                                    Join the Tech Talk
                                                                                                    Success! Thank you! Please check your email for further details.

                                                                                                    Please complete your information!

                                                                                                    Become a contributor for community

                                                                                                    Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                                                                                                    DigitalOcean Documentation

                                                                                                    Full documentation for every DigitalOcean product.

                                                                                                    Resources for startups and SMBs

                                                                                                    The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                                                                                                    Get our newsletter

                                                                                                    Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                                                                                                    New accounts only. By submitting your email you agree to our Privacy Policy

                                                                                                    The developer cloud

                                                                                                    Scale up as you grow — whether you're running one virtual machine or ten thousand.

                                                                                                    Get started for free

                                                                                                    Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                                                                                                    *This promotional offer applies to new accounts only.