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

62 comments on “RESTful Java client with java.net.URL

  1. On my machine(client) is work fine, but on server machine(client) occur exception connection reset while conn.getOutputStream()

  2. Hi mkyong, community,
    trying the sample above, the GET functions very well, but I get a HTTP error 405 for the POST part. What can be the reason pls.?
    FYKI, I create the .war in Netbeans, and deploy the .war onto a Tomcat server under Win 10.

  3. Can you please share example to Call REST service with PATCH method .
    I am getting below error.
    java.net.ProtocolException: Invalid HTTP method: PATCH
    at java.net.HttpURLConnection.setRequestMethod(HttpURLConnection.java:440)

  4. Saludos, Actualmente estoy simulando la combinación de golang con java, esto motivado que ambos pueden trabajar con json.
    El codigo de prueba de golang y funciona es el siguiente.
    ackage main

    import (
    “encoding/json”
    “log”
    “net/http”
    “github.com/gorilla/mux”
    )

    type Person struct {
    ID string json:"id,omitempty"
    FirstName string json:"firstname,omitempty"
    LastName string json:"lastname,omitempty"
    Address *Address json:"address,omitempty"
    }

    type Address struct {
    City string json:"city,omitempty"
    State string json:"state,omitempty"
    }

    var people []Person

    // EndPoints
    func GetPersonEndpoint(w http.ResponseWriter, req *http.Request){
    params := mux.Vars(req)
    for _, item := range people {
    if item.ID == params[“id”] {
    json.NewEncoder(w).Encode(item)
    return
    }
    }
    json.NewEncoder(w).Encode(&Person{})
    }

    func GetPeopleEndpoint(w http.ResponseWriter, req *http.Request){
    json.NewEncoder(w).Encode(people)
    }

    func CreatePersonEndpoint(w http.ResponseWriter, req *http.Request){
    params := mux.Vars(req)
    var person Person
    _ = json.NewDecoder(req.Body).Decode(&person)
    person.ID = params[“id”]
    people = append(people, person)
    json.NewEncoder(w).Encode(people)

    }

    func DeletePersonEndpoint(w http.ResponseWriter, req *http.Request) {
    params := mux.Vars(req)
    for index, item := range people {
    if item.ID == params[“id”] {
    people = append(people[:index], people[index + 1:]…)
    break
    }
    }
    json.NewEncoder(w).Encode(people)
    }

    func main() {
    router := mux.NewRouter()

    // adding example data
    people = append(people, Person{ID: “1”, FirstName:”Ryan”, LastName:”Ray”, Address: &Address{City:”Dubling”, State:”California”}})
    people = append(people, Person{ID: “2”, FirstName:”Maria”, LastName:”Ray”})

    // endpoints
    router.HandleFunc(“/people”, GetPeopleEndpoint).Methods(“GET”)
    router.HandleFunc(“/people/{id}”, GetPersonEndpoint).Methods(“GET”)
    router.HandleFunc(“/people/{id}”, CreatePersonEndpoint).Methods(“POST”)
    router.HandleFunc(“/people/{id}”, DeletePersonEndpoint).Methods(“DELETE”)

    log.Fatal(http.ListenAndServe(“:3000”, router))
    }

    El codigo en java es el siguiente.
    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(“localhost:3000/people/”);
    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();

    }

    }

    }

    Quiero combinar dichos lenguajes, para evaluar su eficiencia y sencilles en construccion, mas otros aspectos, pero me estoy encontrando que java responde con el siguiente error y honestamente no entiendo el porque, disculpen mi falta de conocimiento, pero estoy investigando para evaluar su rendimiento y eficiencia.
    java.net.MalformedURLException: unknown protocol: localhost
    at java.net.URL.(Unknown Source)
    at java.net.URL.(Unknown Source)
    at java.net.URL.(Unknown Source)

    Mil Gracias.

  5. 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

    1. To get you data use ObjectMaper, actually this a class of jackson library, use the below line to get you actual response.
      also you need to create a Product Class with setter and getter method
      Product p= new ObjectMapper().readValue(output, Product.class);

  6. 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();

    1. When you get the parameter in the JSONService function you must use @RequestBody like this

      public Response createProductInJSON(@RequestBody Product product) {}

    1. conn.setRequestProperty(“User-Agent”, “Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36”);

  7. 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();

  8. thank you sir , its really help-full , am wondering if i want to get a lot of products (array) by using the get method , so the problem is how can i store the result (that comes as a String) into a List or an array of objects , thanks again

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

  10. Hej guys, what to change here?
    I have Java 1.8, should I download the older one?
    ERROR (eclipse):
    Build path specifies execution environment JavaSE-1.6. There are no JREs installed in the workspace that are strictly compatible with this environment.

  11. 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"));
    }
    }

  12. ;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}’

  13. Its just awesome, worked for Get, Post and Put request REST APIs without any error.
    Thank you so much

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

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

  16. 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!

  17. 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 🙂

  18. 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..

  19. 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!

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

  21. Hi
    In the Scenario that a client does not know what a service consumes then how would it dynamically find out what a restful service consumes? can you come up with an example?

    cheers
    Alex

  22. 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?

  23. 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)

  24. 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!

  25. 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);
    }

  26. 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.

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

  28. 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

  29. 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

  30. 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);

  31. 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?

    1. Just use the same POST request and change

      connection.setRequestMethod(“POST”);

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

      should work

Leave a Comment

Your email address will not be published. Required fields are marked *