How to send HTTP request GET/POST in Java

http logo

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

  1. Standard HttpURLConnection.
  2. Apache HttpClient library.

1. Java HttpURLConnection example

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

  1. Send an HTTP GET request to Google.com to get the search result.
  2. Send an HTTP POST request to Apple.com search form to check the product detail.
HttpURLConnectionExample.java
package com.mkyong;
 
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
 
import javax.net.ssl.HttpsURLConnection;
 
public class HttpURLConnectionExample {
 
	private final String USER_AGENT = "Mozilla/5.0";
 
	public static void main(String[] args) throws Exception {
 
		HttpURLConnectionExample http = new HttpURLConnectionExample();
 
		System.out.println("Testing 1 - Send Http GET request");
		http.sendGet();
 
		System.out.println("\nTesting 2 - Send Http POST request");
		http.sendPost();
 
	}
 
	// HTTP GET request
	private void sendGet() throws Exception {
 
		String url = "http://www.google.com/search?q=mkyong";
 
		URL obj = new URL(url);
		HttpURLConnection con = (HttpURLConnection) obj.openConnection();
 
		// optional default is GET
		con.setRequestMethod("GET");
 
		//add request header
		con.setRequestProperty("User-Agent", USER_AGENT);
 
		int responseCode = con.getResponseCode();
		System.out.println("\nSending 'GET' request to URL : " + url);
		System.out.println("Response Code : " + responseCode);
 
		BufferedReader in = new BufferedReader(
		        new InputStreamReader(con.getInputStream()));
		String inputLine;
		StringBuffer response = new StringBuffer();
 
		while ((inputLine = in.readLine()) != null) {
			response.append(inputLine);
		}
		in.close();
 
		//print result
		System.out.println(response.toString());
 
	}
 
	// HTTP POST request
	private void sendPost() throws Exception {
 
		String url = "https://selfsolve.apple.com/wcResults.do";
		URL obj = new URL(url);
		HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
 
		//add reuqest header
		con.setRequestMethod("POST");
		con.setRequestProperty("User-Agent", USER_AGENT);
		con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
 
		String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
 
		// Send post request
		con.setDoOutput(true);
		DataOutputStream wr = new DataOutputStream(con.getOutputStream());
		wr.writeBytes(urlParameters);
		wr.flush();
		wr.close();
 
		int responseCode = con.getResponseCode();
		System.out.println("\nSending 'POST' request to URL : " + url);
		System.out.println("Post parameters : " + urlParameters);
		System.out.println("Response Code : " + responseCode);
 
		BufferedReader in = new BufferedReader(
		        new InputStreamReader(con.getInputStream()));
		String inputLine;
		StringBuffer response = new StringBuffer();
 
		while ((inputLine = in.readLine()) != null) {
			response.append(inputLine);
		}
		in.close();
 
		//print result
		System.out.println(response.toString());
 
	}
 
}

Output

Sending 'GET' request to URL : http://www.google.com/search?q=mkyong
Response Code : 200
Google search result...
 
Testing 2 - Send Http POST request
 
Sending 'POST' request to URL : https://selfsolve.apple.com/wcResults.do
Post parameters : sn=C02G8416DRJM&cn=&locale=&caller=&num=12345
Response Code : 200
Apple product detail...

2. Apache HttpClient

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

HttpClientExample.java
package com.mkyong;
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
 
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
 
public class HttpClientExample {
 
	private final String USER_AGENT = "Mozilla/5.0";
 
	public static void main(String[] args) throws Exception {
 
		HttpClientExample http = new HttpClientExample();
 
		System.out.println("Testing 1 - Send Http GET request");
		http.sendGet();
 
		System.out.println("\nTesting 2 - Send Http POST request");
		http.sendPost();
 
	}
 
	// HTTP GET request
	private void sendGet() throws Exception {
 
		String url = "http://www.google.com/search?q=developer";
 
		HttpClient client = new DefaultHttpClient();
		HttpGet request = new HttpGet(url);
 
		// add request header
		request.addHeader("User-Agent", USER_AGENT);
 
		HttpResponse response = client.execute(request);
 
		System.out.println("\nSending 'GET' request to URL : " + url);
		System.out.println("Response Code : " + 
                       response.getStatusLine().getStatusCode());
 
		BufferedReader rd = new BufferedReader(
                       new InputStreamReader(response.getEntity().getContent()));
 
		StringBuffer result = new StringBuffer();
		String line = "";
		while ((line = rd.readLine()) != null) {
			result.append(line);
		}
 
		System.out.println(result.toString());
 
	}
 
	// HTTP POST request
	private void sendPost() throws Exception {
 
		String url = "https://selfsolve.apple.com/wcResults.do";
 
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(url);
 
		// add header
		post.setHeader("User-Agent", USER_AGENT);
 
		List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
		urlParameters.add(new BasicNameValuePair("sn", "C02G8416DRJM"));
		urlParameters.add(new BasicNameValuePair("cn", ""));
		urlParameters.add(new BasicNameValuePair("locale", ""));
		urlParameters.add(new BasicNameValuePair("caller", ""));
		urlParameters.add(new BasicNameValuePair("num", "12345"));
 
		post.setEntity(new UrlEncodedFormEntity(urlParameters));
 
		HttpResponse response = client.execute(post);
		System.out.println("\nSending 'POST' request to URL : " + url);
		System.out.println("Post parameters : " + post.getEntity());
		System.out.println("Response Code : " + 
                                    response.getStatusLine().getStatusCode());
 
		BufferedReader rd = new BufferedReader(
                        new InputStreamReader(response.getEntity().getContent()));
 
		StringBuffer result = new StringBuffer();
		String line = "";
		while ((line = rd.readLine()) != null) {
			result.append(line);
		}
 
		System.out.println(result.toString());
 
	}
 
}

References

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

About the Author

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

Comments

  • http://nitinsurana.com Nitin

    I have to upload file along with other request params. How to achieve that ?

  • tony

    hi there,

    it’s strange – on get request i’ll get the whole HTML Content.

    But when i do a post request, there will be nothing although the response code is 302 (found), the redirect url is the correct one.

    any ideas on this? thanks

  • Onur

    hi

    i want to connect a web service its adreses are

    Web Servisi Adresi :
    real url : https://medeczane.sgk.gov.tr/eczanews/services/SaglikTesisiReceteIslemleri
    Test url : http://saglikt.sgk.gov.tr/eczanews/services/SaglikTesisiReceteIslemleri
    Web Servisi WSDL Adresi :
    real WSDL : https://medeczane.sgk.gov.tr/eczanews/services/SaglikTesisiReceteIslemleri/wsdl/SaglikTesisiReceteIslemleri.wsdl
    Test WSDL: http://saglikt.sgk.gov.tr/eczanews/services/SaglikTesisiReceteIslemleri/wsdl/SaglikTesisiReceteIslemleri.wsdl

    username is 99999999990 and passwork is 99999999990. i must send it with http header to gss server. i must send this request in every SOAP request. can you help me please…

  • H├ęctor

    Hi, I have a problem runing the first example, this is the error:

    java.net.ConnectException: Connection timed out: connect
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
    at java.net.Socket.connect(Socket.java:519)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:550)
    at com.sun.net.ssl.internal.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:141)
    at sun.net.NetworkClient.doConnect(NetworkClient.java:163)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:394)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:529)
    at sun.net.www.protocol.https.HttpsClient.(HttpsClient.java:271)
    at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:328)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:172)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:793)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:158)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:896)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:230)

    Can you help me please?

    PD, Sorry, but I don’t write in english good…

    • http://www.allzhere.in Tarun Trehan

      Hector,

      From the machine where you’re running the program; are you able to open “http://www.google.com/search?q=mkyong” in browser ?

  • http://www.allzhere.in Tarun Trehan

    Hi,

    I am trying to write similar code to check a server status.
    However, i wish to retry up to 5 times in case of failure to connect.
    Is there an option for that ?

    package home.always.learning.java;

    import java.net.ConnectException;
    import java.net.HttpURLConnection;
    import java.net.URL;

    /**
    *
    *
    */
    public class DialServer {

    private static final String url = “http://localhost”;
    private static final String requestMethod = “GET”;

    // HTTP GET request

    public static void main(String[] args) {
    checkServer();
    }

    private static void checkServer() {

    try {
    sendGet();
    } catch (ConnectException e) {
    System.out.println(“Connect Exception..Try Again Till Max Attempts…”);
    e.printStackTrace();
    } catch (Exception e){
    e.printStackTrace();
    }
    }

    private static void sendGet() throws Exception {

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    // optional default is GET
    con.setRequestMethod(requestMethod);
    System.out.println(con.getInputStream());
    int responseCode = con.getResponseCode();
    System.out.println(“Response Code : ” + responseCode);
    }
    }

    • Alex

      You could check for other status codes, and using _if-esle_ you could call for the function again(for example if status is not(200)). To set it to check 5 times you could use a _for_ loop. Here is the list of http status codes: http://en.wikipedia.org/wiki/List_of_HTTP_status_codes

      • http://www.allzhere.in Tarun Trehan

        Alex,
        Thanks for your response. I did put the code to run in a loop and succeeded. However, if the server i am pinging is offline; i get a connect exception. Hence, i have to initiate my code to check again from the catch block. Per standards, is that a good thing to do, i.e. initiate a possible processing logic from catch block ???
        Else, i did get the code to work.

        public static void checkServer() {

        for (int i = 0; i <= maxAttempts; i++) {
        try {
        int responseCode = sendGet();
        if(responseCode==200)
        {
        System.out.println("Break Loop and Return");
        break;
        }
        } catch (ConnectException e) {
        if(i==maxAttempts)
        {
        System.out.println("Max Attempts Have Reached for Server Response…ALERT Now");
        }
        else
        {
        System.out.println("Connect Exception..Try Again Till Max Attempts…");
        try {
        Thread.currentThread().sleep(retryPeriod);
        } catch (InterruptedException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        }
        }
        } catch (Exception e) {
        System.out.println("Generic Exception Connecting To Server…");
        e.printStackTrace();
        }
        }
        }

        • http://learnbymac.com Kaydell Leavitt

          “is that a good thing to do, i.e. initiate a possible processing logic from catch block ???”

          I haven’t studied your code thouroughly, but I think that catching exceptions and trying a gin is one of the whole points of try-catch blocks. To have exceptions and still keep the program run without terminating with an exception thrown from the main() method.

          • http://www.allzhere.in Tarun Trehan

            I have asked for a review on the same point but did not receive much inputs.
            However, i have observed some business scenarios where a business action will be performed in case an exception occurred. Considering this, i wrote the code involving catch.
            Another reason was that if the server was not online; Java was throwing a connect exception and not giving some “code” to check the status. Else, an if-else construct would have helped me.

          • http://www.allzhere.in Tarun Trehan

            I wrote a program to implement my use case for recursive call to check server status periodically.
            Following is the link to my post :

            http://allzhere.in/2013/09/13/java-ping-server-status/

  • lihao

    Good.

    but,
    spring mvc.
    RestTemplate example?

  • Aman Gupta

    Excellent examples over GET and POST method.

  • http://www.maasmind.com/java-training.htm java training in chennai

    Good one. The output is displayed in html source format.