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

About the Author

author image
mkyong
Founder of Mkyong.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

Leave a Reply

avatar
newest oldest most voted
maddy
Guest
maddy

Hi

Exception in thread “main” java.lang.RuntimeException: Failed : HTTP error code : 403

Jesus David Sanchez Suarez
Guest
Jesus David Sanchez Suarez

I have an error consuming the service:
java.net.ConnectException: Connection refused: connect….
I could not find any errors

Guest
Guest
Guest

using the above code i am not able to pass the request body to the api. the following code is not working for me:
String input = “{“qty”:100,”name”:”iPad 4″}”;

OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();

Tia
Guest
Tia

I implemented the same code for PostClient but its returning the object and not the json as shown in output result..

As Shown above
Output from Server ….

Product created : Product [name=iPad 4, qty=100]

My implementation result
Output from Server ….

Product created atLL: com.rest.resteasy.DeviceVO@6f075e05

Paxi
Guest
Paxi

Hi,
I had a problem with this code, but successfully i got handle it (I set wrong parameters to setRequestProperty). Now my code is works, but i get an error message this part:

if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException(“Failed : HTTP error code : ”
+ conn.getResponseCode());
}
My error code is 200, which it means everything ok. Why?

asd
Guest
asd

i am getting 411 exception

yeni
Guest
yeni

hi
serverError: class java.lang.RuntimeException

srinivas
Guest
srinivas

Can we create a connection from myapplication to any other website using api key with this example ? If it possible how ?

tushar banne
Guest
tushar banne

In 1. GET Request, is it a stateless Call or Satefull call?

How do I identify it?

SUMIT
Guest
SUMIT

Hey, I have solution for this

Kanishk Jadhav
Guest
Kanishk Jadhav

Hi,
I am getting below exception at “DataOutputStream wr = new DataOutputStream(con.getOutputStream());” this statement.
“javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?”

Below is the code:
HttpURLConnection con;
String inputLine;
StringBuffer response=null;

try {
URL obj = new URL(null, url, new sun.net.www.protocol.https.Handler());
con = (HttpURLConnection) obj.openConnection(); //(HttpsURLConnection)

con.setRequestMethod(“POST”);
con.addRequestProperty(“Content-Type”,”application/json”);

for(Map.Entry prop : header.entrySet()) {
con.setRequestProperty(prop.getKey(),prop.getValue());
}

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

Vin
Guest
Vin

Hi,
I am trying to call Rest api and then parse the values .my code is throwing a null pointer exception at this stage .PLEASE can you help me
JSONArray jsonarr_1=(JSONArray)jobj.get(“collection”);
int n=(out1).length();
for (int i=0;i<n;++i)
{
JSONObject jsonobj_1=(out1).getJSONObject(i);/////////////null pointer exception
System.out.println("nSureLinks:"+jsonobj_1.get("element"));
}
}

MARIO GOMES
Guest
MARIO GOMES

;Hi Mkyong

Can you help me where i can send the : “chave”:45150819652219000198550990000000011442380343 in json method GET
?

curl -X GET
-H “X-Consumer-Key: SEU_CONSUMER_KEY”
-H “X-Consumer-Secret: SEU_CONSUMER_SECRET”
-H “X-Access-Token: SEU_ACCESS_TOKEN”
-H “X-Access-Token-Secret: SEU_ACCESS_TOKEN_SECRET”
-H “Content-Type: application/json”
-d ‘{“chave”:45150819652219000198550990000000011442380343}’

Sanket Khandekar
Guest
Sanket Khandekar

Hi Nice Post

Just wanted to know if my url is https will this allow ?

Partha Malik
Guest
Partha Malik

I need to put “application/json; version=1” in request header but that gives a parse exception. How to solve that??

Justin Amburn
Guest
Justin Amburn

So many high quality tutorials on this website. Has saved much time with building/consuming REST service and API. Thank you very much.

Asif Malek
Guest
Asif Malek

Thanks mkYong..for saving my job :)… keep it up

spikeTJ
Guest
spikeTJ

Hi! i have to build a rest client for a Maven, Spring and cxf web services? Its thats way above works? Thanks for your help!

Pratap A.K
Guest
Pratap A.K

You are such an excellent guide, nice tutorial
Thanks for the topic

Ali Abbas
Guest
Ali Abbas

I’m getting below error while calling getOutputStream in Delete request.

ERROR : java.net.ProtocolException: HTTP method DELETE doesn’t support output

What i wanted is to call delete request with body.

Any help will be highly appreciated :)

Bikash Singh
Guest
Bikash Singh

Use below additional dependency to fix the issue.

com.sun.jersey

jersey-json

1.8

John
Guest
John

Hi,

I’m getting this error: Connection refused: connect.

in this line: OutputStream os = conn.getOutputStream();

Can you help me with this issue ?

Thank you in advance..

Raj
Guest
Raj

How can I add http authentication header in this ?

Good Nature
Guest
Good Nature

Try looking at http-rest-client

https://github.com/g00dnatur3/http-rest-client

Here is a simple example:

RestClient client = RestClient.builder().build();

String geocoderUrl = “http://maps.googleapis.com/maps/api/geocode/json”

Map params = Maps.newHashMap();

params.put(“address”, “beverly hills 90210”);

params.put(“sensor”, “false”);

JsonNode node = client.get(geocoderUrl, params, JsonNode.class);

Cheers!

Alex Martinson
Guest
Alex Martinson

What I meant was how would you dynamically find out about the supported mime types by a restful resource before consuming the resource.

Shah Mujtaba ALi
Guest
Shah Mujtaba ALi

Hi

Thanks for the sharing, please let me know how can we add authorization parameters ?

Pramod
Guest
Pramod

Can we run both REST server and Client project in a same machine? Please explain

satish
Guest
satish

unable to run example : getting below error after deploy into tomcat

May 05, 2014 4:24:17 PM org.apache.catalina.core.StandardContext listenerStart

SEVERE: Error configuring application listener of class org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap

java.lang.ClassNotFoundException: org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap

at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1720)

at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1571)

at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:529)

at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:511)

at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:139)

at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4888)

at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5467)

at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)

at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)

at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)

Amrutha Valli
Guest
Amrutha Valli

hi
Can u help me to cosume a json and produce a json using restful webservice

trackback
JAX-RS TUTORIALS | BUYWORKSELL

[…] RESTful Java client with java.net.URL […]