RESTful Java client with java.net.URL

In this tutorial, we show you how to create a RESTful Java client with Java build-in HTTP client library. It’s simple to use and good enough to perform basic operations for REST service.

The RESTful services from last “Jackson + JAX-RS” article will be reused, and we will use “java.net.URL” and “java.net.HttpURLConnection” to create a simple Java client to send “GET” and “POST” request.

1. GET Request

Review last REST service, return “json” data back to client.

@Path("/json/product")
public class JSONService {
 
	@GET
	@Path("/get")
	@Produces("application/json")
	public Product getProductInJSON() {
 
		Product product = new Product();
		product.setName("iPad 3");
		product.setQty(999);
 
		return product; 
 
	}
	//...

Java client to send a “GET” request.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
 
public class NetClientGet {
 
	// http://localhost:8080/RESTfulExample/json/product/get
	public static void main(String[] args) {
 
	  try {
 
		URL url = new URL("http://localhost:8080/RESTfulExample/json/product/get");
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");
		conn.setRequestProperty("Accept", "application/json");
 
		if (conn.getResponseCode() != 200) {
			throw new RuntimeException("Failed : HTTP error code : "
					+ conn.getResponseCode());
		}
 
		BufferedReader br = new BufferedReader(new InputStreamReader(
			(conn.getInputStream())));
 
		String output;
		System.out.println("Output from Server .... \n");
		while ((output = br.readLine()) != null) {
			System.out.println(output);
		}
 
		conn.disconnect();
 
	  } catch (MalformedURLException e) {
 
		e.printStackTrace();
 
	  } catch (IOException e) {
 
		e.printStackTrace();
 
	  }
 
	}
 
}

Output…

Output from Server .... 
 
{"qty":999,"name":"iPad 3"}

2. POST Request

Review last REST service, accept “json” data and convert it into Product object, via Jackson provider automatically.

@Path("/json/product")
public class JSONService {
 
        @POST
	@Path("/post")
	@Consumes("application/json")
	public Response createProductInJSON(Product product) {
 
		String result = "Product created : " + product;
		return Response.status(201).entity(result).build();
 
	}
	//...

Java client to send a “POST” request, with json string.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
 
public class NetClientPost {
 
	// http://localhost:8080/RESTfulExample/json/product/post
	public static void main(String[] args) {
 
	  try {
 
		URL url = new URL("http://localhost:8080/RESTfulExample/json/product/post");
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setDoOutput(true);
		conn.setRequestMethod("POST");
		conn.setRequestProperty("Content-Type", "application/json");
 
		String input = "{\"qty\":100,\"name\":\"iPad 4\"}";
 
		OutputStream os = conn.getOutputStream();
		os.write(input.getBytes());
		os.flush();
 
		if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
			throw new RuntimeException("Failed : HTTP error code : "
				+ conn.getResponseCode());
		}
 
		BufferedReader br = new BufferedReader(new InputStreamReader(
				(conn.getInputStream())));
 
		String output;
		System.out.println("Output from Server .... \n");
		while ((output = br.readLine()) != null) {
			System.out.println(output);
		}
 
		conn.disconnect();
 
	  } catch (MalformedURLException e) {
 
		e.printStackTrace();
 
	  } catch (IOException e) {
 
		e.printStackTrace();
 
	 }
 
	}
 
}

Output…

Output from Server .... 
 
Product created : Product [name=iPad 4, qty=100]

Download Source Code

Download it – JAX-RS-Client-JavaURL-Example.zip (8 KB)

References

  1. Jackson Official Website
  2. java.net.URL JavaDoc
  3. java.net.HttpURLConnection JavaDoc
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

  • Pingback: Blue Coaster33()

  • Pingback: JAX-RS TUTORIALS | BUYWORKSELL()

  • http://ry-veretekk42.blogspot.com/2013/08/free-twitter-leads.html Luisa Spickerman

    Spot on with this write-up, I actually assume this web site wants far more consideration. I?ll in all probability be once more to learn far more, thanks for that info.

  • http://www.df22lkhddfsd.com/u33ss Merrill Monaco

    So attractive! I like the earthy & classic tones with the wedding! I am so stealing the succulent idea. Beautiful bride, handsome hubby & bridal party. Incredible images as usually Tammy!

  • Kasi

    Hi,
    I am having trouble with getting response back. here my code, can you please comment on whats wrong. Appreciate your quick reply.

    Error : java.net.SocketException: Unexpected end of file from server

    String name = “xxxx”;
    String password = “xxxx”;
    String authString = name + “:” + password;
    byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
    String authStringEnc = new String(authEncBytes);
    System.out.println(“Base64 encoded auth string: ” + authStringEnc);
    String urlString=”http://xxxx.com:8080/cms/stss/active-calls”;
    String input =”{\”search.callid\”:364-19635@xxxxxx}”;
    //String jsonString=”&output=json”;
    urlString +=input;
    URL url = new URL(urlString);

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

    conn.setInstanceFollowRedirects(false);
    conn.setDoOutput(true);
    conn.setRequestMethod(“POST”);
    conn.setRequestProperty(“Content-Type”, “application/json”);
    conn.setRequestProperty(“Authorization”, “Basic”+authStringEnc);

    OutputStream os = conn.getOutputStream();
    os.write(input.getBytes());
    os.flush();
    System.out.println(conn.getURL());
    if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
    throw new RuntimeException(“Failed : HTTP error code : ”
    + conn.getResponseCode());

    }

    Charset charset = Charset.forName(“UTF-8″);
    InputStreamReader stream = new InputStreamReader(conn.getInputStream(), charset);
    // BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

    BufferedReader reader = new BufferedReader(stream);
    StringBuffer responseBuffer = new StringBuffer();

    String read = “”;
    while ((read = reader.readLine()) != null) {
    responseBuffer.append(read);
    }

  • garry

    I tried running the post example but in getting the below exception.
    Plz suggest

    E org.apache.wink.server.internal.handlers.FlushResultHandler handleResponse The system could not find a javax.ws.rs.ext.MessageBodyWriter or a DataSourceProvider class for the com.rest.assignment.Product type and application/json mediaType. Ensure that a javax.ws.rs.ext.MessageBodyWriter exists in the JAX-RS application for the type and media type specified.

  • Jason Parraga

    Thanks Mykong, you’re the best. Needed to know how to set request headers in a get request and this was perfect!

  • Pallavi

    hi,
    Iam trying to create registrant for webinar session in java. but im getting exception as “Exception in thread “main” java.lang.RuntimeException: Failed : HTTP error code : 400″.
    Following is the code :

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.io.OutputStreamWriter;
    import javax.net.ssl.HttpsURLConnection;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.List;
    import org.apache.http.HttpResponse;
    import net.sf.json.JSONArray;
    import net.sf.json.JSONObject;

    URL url = new URL(“https://api.citrixonline.com/G2W/rest/organizers/1992996/webinars/201017049/registrants?oauth_token=eea96a14954693c80039d6cbf3f2e4c1″);

    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setRequestMethod(“POST”);
    conn.setRequestProperty(“Content-type”,”application/json”);
    conn.setRequestProperty(“Accept”, “application/json”);
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setAllowUserInteraction(true);

    JSONObject object=new JSONObject();
    object.put(“mail”,”[email protected]”);
    object.put(“firstName”,”Pallavi”);
    object.put(“lastName”,”Mali”);

    OutputStream os = conn.getOutputStream();
    os.write(object.toString().getBytes());
    conn.connect();

    if (conn.getResponseCode() != 200)
    {
    throw new RuntimeException(“Failed : HTTP error code : “+ conn.getResponseCode());
    }

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

    String output;
    System.out.println(“Output from Server …. \n”);
    while ((output = br.readLine()) != null) {
    System.out.println(output);
    }

    conn.disconnect();

    Plz help me.
    thanks in advance.

    Regards,
    Pallavi

    • Pallavi

      i tried this one also:

      String input = “{\”mail\”:\”[email protected]\”,\”firstName\” : \”Amrit\”,\”lastName\” : \”Ansarwadkar\”}”;

  • Akhil

    perfect one….!!!

    Great job… Well explained.

  • Pingback: Simple RESTful Java client in Google App Engine using java.net.URL | BlogoSfera()

  • Gus

    Thanks mkyong.

    As a Java programmer completely new to json, this article provided all the information I needed to understand how to request data from a json API.

    Since the service I’m connecting to is https, the only major changes I needed to make were:

    substitute

    import javax.net.ssl.HttpsURLConnection;

    for

    import java.net.HttpURLConnection;

    and, in the code:

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

    instead of

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

    I also had to change:

    if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
    			throw new RuntimeException("Failed : HTTP error code : "
    				+ conn.getResponseCode());
    		}

    to

    if (conn.getResponseCode() != 200) 
    							{
    								throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
    							}

    otherwise the exception was thrown even when the connection had been correctly established.

    to

    instead of

  • Pingback: JSON World Bank Data in NetBeans HTML Code Completion | Strategic HR()

  • Azhar

    Great article.

    I am unable to form the request parameter for consuming REST web service GET and POST, could any one please guide based on below scenario.

    If I have REST webservice as below which is expecting two string parameters

    General Web URL to consume webservice :

    http://localhost:8080/myWs/sayHello?name=Peter&msg=Hai

    //How to pass the arguments for getting GET and POST result.

    org.springframework.web.client.RestTemplate restTemplate = new RestTemplate();
    String url = “http://localhost:8080/myWs/sayHello”;
    Map vars = new HashMap();
    vars.put(“name”, “peter”);
    vars.put(“msg”, “Hai”);
    String result = restTemplate.getForObject(url+”/{name}/{msg}”, String.class, vars);
    String result1 = restTemplate.postForObject(url, vars,String.class);

    System.out.println(“GET result : “+result + “\nPOST result1″+result1);

  • Pingback: RESTful Java client with RESTEasy client framework()

  • Pingback: RESTful Java client with Jersey client()

  • http://www.rantingsofaravinglunatic.com Karthic

    Great article. I used this to create my Java client to talk to a .NET WebAPI REST service that I created. Works like a charm.

    Can you also add a PUT and DELETE snippet to make this post a complete tutorial?

    • http://www.dumparun.info Arun

      Just use the same POST request and change

      connection.setRequestMethod(“POST”);

      to
      connection.setRequestMethod(“PUT”);
      connection.setRequestMethod(“DELETE”);

      should work

  • Pingback: RESTful Java client with Apache HttpClient()