05. REST Clients & POST requests
1. Client code
Let's suppose we have a REST server ON that offers its services.
Here is a simple client class code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | package org.ximodante.jaxrs.client; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; public class RestAPIClient01 { public static void main(String[] args) { // 01. Create client Client client = ClientBuilder.newClient(); //02. Get a Response calling the client Response response = //03. Tell a URL to call (target) client.target("http://localhost:8080/Jaxrs02/messages/1") // This produces a WebTarget //04. Get the request. We can specify it type or not // if we specify type : //.request(MediaType.APPLICATION_JSON) // or not: .request() // This produces a Builder //05. Do a GET // We can unwrap or not the class we read, if so: //.get(MyMessage.class); //if not: .get(); // This, evidently produces a Response //06. Response is a wrapper of our message class. Our class may be MyMessage MyMessage message =response.readEntity(MyMessage.class); //07. But it the message cannot be unmarshalled then use String.class instead of MyMessage.class //String message =response.readEntity(String.class); //08. See the results System.out.println(message); } } |
The code is well explained
In Line 15, response represents an object wrapper of a class called MyMessage. We need to pass the URL, make the request and use GET. As it is commented if an unmarshalling error occurs we can use a String class to retrieve the "bulk" response and analyze it.
Here is the MyMessage class
1 2 3 4 5 6 7 8 9 10 11 | package org.ximodante.jaxrs.client; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.AllArgsConstructor; @NoArgsConstructor @AllArgsConstructor public class MyMessage { @Getter @Setter private int id=0; @Getter @Setter private String description; } |
2. Best practices
In Java Brains, it is recommended to use a base WebTarget element and decline paths and variables. In this class a variable "{messageId}"Here is the code with several messages:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | package org.ximodante.jaxrs.client; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; public class RestAPIClient02 { public static void main(String[] args) { // 01. Create client Client client = ClientBuilder.newClient(); //02. We can get multiple target instances referenced from baseTarget WebTarget baseTarget = client.target("http://localhost:8080/Jaxrs02"); WebTarget msgTarget= baseTarget.path("message"); WebTarget msgSelectTarget= msgTarget.path("{messageId}"); // A variable or parameter is used //03. Pass the parameter value and select the media type MyMessage msg1 =msgSelectTarget .resolveTemplate("messageId","1") .request(MediaType.APPLICATION_JSON) .get(MyMessage.class); //03.b.Other parameter MyMessage msg2 =msgSelectTarget .resolveTemplate("messageId","2") .request(MediaType.APPLICATION_JSON) .get(MyMessage.class); //04. Output results System.out.println(msg1); System.out.println(msg2); } } |
3. Post
To do a POST we need to pass an object to the request, in this case, is a MyMessage type. We want to create a new message.
Let's change the lines after line 30 with these lines.
Notice :
- the creation of a POST request
- the class Entity that wraps the MyMessage object
- getting the object from the response
- checking the status of the response. If not "201" then an error has occurred!
//04. POST with new created object MyMessage newMsg=new MyMessage(3,"The third message"); Response postResp=msgTarget .request() .post(Entity.json(newMsg)); //05. Test Errors MyMessage createdMsg=postResp.readEntity(MyMessage.class);if (postResp.getStatus() !=201) {System.out.println("Error occurred!");}
//06. Output results System.out.println(msg1); System.out.println(msg2); System.out.println(createdMsg); } }
But if we want to update an object (of type MyMessage) , for instance with id=1, we need to POST the object to the WebTarget msgSelectTarget and the messageId should have value "1", so that we can update it.
So we can use POST request to create new objects and for updating existing objects.
The response object apart from giving information about status it also has methods that supply information about:
- cookies
- headers
Comentarios
Publicar un comentario