GET/POST request with HttpURLConnection in Java

  • 17 October 2016
  • ADM

 

GET/POST request with HttpURLConnection in Java - images/logos/java.jpg

 

In this tutorial will cover how to do GET and POST request using HttpURLConnection class from Java without any 3rd party library.

First, we need a test server and for this I will use httpbin.org. This test server contains a lot of useful endpoints for testing. In this tutorial will use 2 of them:

For the User-Agent header I will use an random agent picked up from useragentstring.com.

Example

package com.admfactory.http;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpURLConnectionExample {

    private static final String USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36";

    public void post(String url, String params) throws Exception {
	String result = null;

	URL obj = new URL(url);
	HttpURLConnection con = (HttpURLConnection) obj.openConnection();

	con.setRequestMethod("POST");
	con.setRequestProperty("User-Agent", USER_AGENT);

	con.setDoOutput(true);
	DataOutputStream wr = new DataOutputStream(con.getOutputStream());
	wr.writeBytes(params);
	wr.flush();
	wr.close();

	int responseCode = con.getResponseCode();
	System.out.println("'POST' request to URL : " + url);
	System.out.println("Response Code : " + responseCode);

	System.out.println("Response Body : ");
	BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
	String inputLine;
	StringBuffer response = new StringBuffer();

	while ((inputLine = in.readLine()) != null) {
	    response.append(inputLine);
	}
	in.close();

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

    }

    public void get(String url, String params) throws Exception {
	String result = null;

	URL obj = new URL(url + "?" + params);
	HttpURLConnection con = (HttpURLConnection) obj.openConnection();

	con.setRequestMethod("GET");

	con.setRequestProperty("User-Agent", USER_AGENT);

	int responseCode = con.getResponseCode();
	System.out.println("'GET' request to URL : " + url);
	System.out.println("Response Code : " + responseCode);

	System.out.println("Response Body : ");
	BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
	String inputLine;
	StringBuffer response = new StringBuffer();

	while ((inputLine = in.readLine()) != null) {
	    response.append(inputLine);
	}
	in.close();

	result = response.toString();
	System.out.println(result);
    }

    public static void main(String[] args) {
	try {
	    HttpURLConnectionExample example = new HttpURLConnectionExample();
	    String getUrl = "http://httpbin.org/get";

	    System.out.println("HttpURLConnection Examples:");
	    System.out.println();
	    example.get(getUrl, "param1=123&param2=abc");
	    System.out.println();

	    String postUrl = "http://httpbin.org/post";
	    example.post(postUrl, "param3=345&param4=ert");

	} catch (Exception e) {
	    e.printStackTrace();
	}
    }
}

If you need to call an HTTPS service then HttpsURLConnection need to be used instead of HttpURLConnection.

Output

HttpURLConnection Examples:

'GET' request to URL : http://httpbin.org/get
Response Code : 200
Response Body : 
{  "args": {    "param1": "123",     "param2": "abc"  },   "headers": {    "Accept": "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2",     "Cache-Control": "max-age=259200",     "Host": "httpbin.org",     "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36"  },   "url": "http://httpbin.org/get?param1=123&param2=abc"}

'POST' request to URL : http://httpbin.org/post
Response Code : 200
Response Body : 
{  "args": {},   "data": "",   "files": {},   "form": {    "param3": "345",     "param4": "ert"  },   "headers": {    "Accept": "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2",     "Cache-Control": "max-age=259200",     "Content-Length": "21",     "Content-Type": "application/x-www-form-urlencoded",     "Host": "httpbin.org",     "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36"  },   "json": null,   "url": "http://httpbin.org/post"}

Note: Your response will be longer that my output. I removed some data that contains my IP address.

 

References