Passing an Object to a REST Web Service Using Knitwear

I have a simple WS that is @PUT and accepts an object

 @Path("test") public class Test { @PUT @Path("{nid}"} @Consumes("application/xml") @Produces({"application/xml", "application/json"}) public WolResponse callWol(@PathParam("nid") WolRequest nid) { WolResponse response = new WolResponse(); response.setResult(result); response.setMessage(nid.getId()); return response; } 

and my client side code ...

 WebResource wr = client.resource(myurl); WolResponse resp = wr.accept("application/xml").put(WolResponse.class, wolRequest); 

I am trying to pass an instance of WolRequest to @PUT Webservice. I constantly get 405 errors trying to do this.

How to transfer an object from a client to a server through Jersey? Am I using a query parameter or query?

Both of my POJOs ( WolRequest and WolResponse ) have an XMlRootElement tag, so I can produce and consume xml ..

+4
source share
5 answers

I think using @PathParam is wrong here. A @PathParam can basically be a String (see Its javadoc for more information).

You can: 1) use the @PathParam parameter as a String or 2) not define a WolRequest as @PathParam.

one)

 @Path("test") public class Test { @PUT @Path("{nid}"} @Consumes("application/xml") @Produces({"application/xml", "application/json"}) public WolResponse callWol(@PathParam("nid") String nid) { WolResponse response = new WolResponse(); response.setResult(result); response.setMessage(nid); return response; } 

This will accept URLs such as: "text / 12", 12 - String nid. This is not like it will help what you are trying to do.

or

2)

 @Path("test") public class Test { @PUT @Consumes("application/xml") @Produces({"application/xml", "application/json"}) public WolResponse callWol(WolRequest nid) { WolResponse response = new WolResponse(); response.setResult(result); response.setMessage(nid.getId()); return response; } 

Your client code may be what you specified, only the URL for PUT: "test". Perhaps you need a combination of both one @PathParam for your identifier and one β€œnormal” parameter to get your request data.

Hope this helps.

+1
source

Check this link http://www.vogella.de/articles/REST/article.html

According to the sample code of the putTodo method of the TodoResource class, your code should be like this.

 @Path("test") public class Test{ @PUT @Consumes("application/xml") @Produces({"application/xml", "application/json"}) public WolResponse callWol(JAXBElement<WolRequest> nid) { WolResponse response = new WolResponse(); response.setResult(result); response.setMessage(nid.getValue().getId()); return response; } } 

Hope this solves your problem.

Greetings

+1
source

You can try something like this

 @POST @Path("/post") @Consumes(MediaType.APPLICATION_XML) @Produces(MediaType.APPLICATION_XML) public Response callWol(WolRequest nid) { WolResponse response = new WolResponse(); response.setResult(result); response.setMessage(nid.getValue().getId()); return Response.status(Status.OK).entity(response).build(); } 

You can also try @PUT instead of @Post. Hope this helps

0
source

I had the same problem that I solved in 3 steps with Jackson in Netbeans / Glashfish btw.

1) Requirements:

Some of the boxes I used:

  commons-codec-1.10.jar commons-logging-1.2.jar log4j-1.2.17.jar httpcore-4.4.4.jar jackson-jaxrs-json-provider-2.6.4.jar avalon-logkit-2.2.1.jar javax.servlet-api-4.0.0-b01.jar httpclient-4.5.1.jar jackson-jaxrs-json-provider-2.6.4.jar jackson-databind-2.7.0-rc1.jar jackson-annotations-2.7.0-rc1.jar jackson-core-2.7.0-rc1.jar 

If I missed any of the cans above, you can download from Maven here http://mvnrepository.com/artifact/com.fasterxml.jackson.core

2) The Java class where you are sending the message. First, convert with Entity user Jackson to Json, and then send him to your vacation class.

 import com.fasterxml.jackson.databind.ObjectMapper; import ht.gouv.mtptc.siiv.model.seguridad.Usuario; import java.io.IOException; import java.io.UnsupportedEncodingException; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.json.simple.JSONObject; public class PostRest { public static void main(String args[]) throws UnsupportedEncodingException, IOException { // 1. create HttpClient DefaultHttpClient httpclient = new DefaultHttpClient(); // 2. make POST request to the given URL HttpPost httpPost = new HttpPost("http://localhost:8083/i360/rest/seguridad/obtenerEntidad"); String json = ""; Usuario u = new Usuario(); u.setId(99L); // 3. build jsonObject JSONObject jsonObject = new JSONObject(); jsonObject.put("id", u.getId()); // 4. convert JSONObject to JSON to String //json = jsonObject.toString(); // ** Alternative way to convert Person object to JSON string usin Jackson Lib //ObjectMapper mapper = new ObjectMapper(); //json = mapper.writeValueAsString(person); ObjectMapper mapper = new ObjectMapper(); json = mapper.writeValueAsString(u); // 5. set json to StringEntity StringEntity se = new StringEntity(json,"UTF-8"); // 6. set httpPost Entity httpPost.setEntity(se); // 7. Set some headers to inform server about the type of the content httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-type", "application/json"); // 8. Execute POST request to the given URL HttpResponse httpResponse = httpclient.execute(httpPost); // 9. receive response as inputStream //inputStream = httpResponse.getEntity().getContent(); } } 

3) Java Class Rest, where you want to get Entity JPA / Hibernate. Here with your MediaType.APPLICATION_JSON you get the object like this:

"Identifier": 99 , "usuarioPadre": zero, "nickname": zero, "clave": zero, "Nombre": NULL, "apellidos": zero, "isLoginWeb": zero, "isLoginMovil": zero, "Estado ": null," correoElectronico ": null," imagePerfil ": null," Perfil ": null," urlCambioClave ": null," Telefono ": null," Celular ": null" isFree ": null," proyectoUsuarioList ": null , "cuentaActiva": null, "keyUser": null, "isCambiaPassword": null, "videoList": null, "idSocial": null, "tipoSocial": null, "idPlanActivo": null, "cantidadMbContratado": null, " cantidadMbConsumido ": null," cuotaMb ": null," fechaInicio ": null," fechaFin ": null}"

  import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.apache.log4j.Logger; @Path("/seguridad") public class SeguridadRest implements Serializable { @POST @Path("obtenerEntidad") @Consumes(MediaType.APPLICATION_JSON) public JSONArray obtenerEntidad(Usuario u) { JSONArray array = new JSONArray(); LOG.fatal(">>>Finally this is my entity(JPA/Hibernate) which will print the ID 99 as showed above :" + u.toString()); return array;//this is empty } .. 

Some tips. If you have problems starting the network after using this code, possibly due to @Consumes in XML ... you should set it as @Consumes(MediaType.APPLICATION_JSON)

0
source

Try it, it will work

Server side:

 @PUT @Consumes(MediaType.APPLICATION_XML) @Produces(MediaType.APPLICATION_XML) public String addRecord(CustomClass mCustomClass) { /// /// /// return "Added successfully : "+CustomClass.getName(); }// addRecord 

Client side:

 public static void main(String[] args) { /// /// /// CustomClass mCustomClass = new CustomClass(); Client client = ClientBuilder.newClient(); String strResult = client.target(REST_SERVICE_URL).request(MediaType.APPLICATION_XML).put(Entity.xml(mCustomClass), String.class); } 
0
source

All Articles