使用Jersey将对象传递给REST Web服务

我有一个简单的WS,它是一个@PUT并且接受一个对象

 @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; } 

我的客户端代码是……

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

我试图将WolRequest的实例传递给@PUT Webservice。 试图这样做我经常遇到405错误。

如何通过Jersey将对象从客户端传递到服务器? 我使用查询参数还是请求?

我的POJO( WolRequestWolResponse )都定义了XMlRootElement标记,因此我可以生成和使用xml ..

我认为@PathParam的用法在这里是不正确的。 @PathParam基本上可以是一个String(有关更多信息,请参阅其javadoc)。

您可以1)使用@PathParam作为String参数或2)不要将WolRequest定义为@PathParam。

1)

 @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; } 

这将接受以下url:“text / 12”,然后12将成为String nid。 看起来这不会有助于您尝试做什么。

要么

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; } 

您的客户端代码可以像您指定的那样,只有PUT的URL是:“test”。 也许你需要为你的id和一个“普通”参数组合使用一个@PathParam来获取你的请求数据。

我希望这有帮助。

查看此链接http://www.vogella.de/articles/REST/article.html

根据类TodoResource的方法putTodo的代码示例,您的代码应该是这样的。

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

希望这能解决你的问题。

干杯

你可以尝试这样的事情

 @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(); } 

您也可以尝试@PUT而不是@Post。 希望这可以帮助

我遇到了同样的问题,我在Netbeans / Glashfish btw中用jackson的 3个步骤解决了。

1)要求:

我使用的一些jar子:

  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 

如果我错过了上面的任何一个jar,你可以从Maven下载http://mvnrepository.com/artifact/com.fasterxml.jackson.core

2)发送post的Java类。 首先,将jackson的实体用户转换为Json,然后将其发送到您的Rest 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你想要接收Entity JPA / Hibernate。 在这里使用MediaType.APPLICATION_JSON,您可以通过以下方式接收实体:

“”id“: 99 ,”usuarioPadre“:null,”nickname“:null,”clave“:null,”nombre“:null,”apellidos“:null,”isLoginWeb“:null,”isLoginMovil“:null,”埃斯塔 “:空,” correoElectronico “:空,” imagePerfil “:空,” PERFIL “:空,” urlCambioClave “:空,” telefono “:空,” celular “:空,” isFree “:空,” proyectoUsuarioList” :空, “cuentaActiva”:空, “keyUser”:空, “isCambiaPassword”:空, “videoList”:空, “idSocial”:空, “tipoSocial”:空, “idPlanActivo”:空, “cantidadMbContratado”:空“cantidadMbConsumido”:空, “cuotaMb”:空, “fechaInicio”:空, “fechaFin”:空}”

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

一些提示:如果在使用此代码后运行Web时遇到问题可能是因为@Consumes in XML中的@Consumes in XML …您必须将其设置为@Consumes(MediaType.APPLICATION_JSON)

试试这个它会起作用

服务器端:

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

客户端:

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