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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1990988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 02:10:30  来源:igfitidea点击:

Passing an object to a REST Web Service using Jersey

javajersey

提问by matchan

I have a simple WS that is a @PUTand takes in an object

我有一个简单的 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;
    }

and my client side code is...

我的客户端代码是...

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

I am trying to pass an instance of WolRequestinto the @PUTWebservice. I am constantly getting 405 errors trying to do this..

我正在尝试将 的实例传递WolRequest@PUTWeb 服务中。尝试执行此操作时,我不断收到 405 错误。

How can I pass an object from the client to the server via Jersey ? Do I use a query param or the request ?

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

Both my POJOs (WolRequestand WolResponse) have the XMlRootElementtag defined so i can produce and consume xml..

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

回答by PD.

I think the usage of the @PathParam is not correct here. A @PathParam is can basically be a String (see its javadoc for more info).

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

You can 1) use the @PathParam as a String parameter or 2) don't define WolRequest as a @PathParam.

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

1)

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

This will accept urls like: "text/12", 12 will then be the String nid. It doesn't look like this will help what you are trying to do.

这将接受如下网址:“text/12”,然后 12 将是字符串 nid。看起来这对您正在尝试做的事情没有帮助。

or

或者

2)

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 can be like you specified, only the url for PUT is: "test". Perhaps you need a combination of both one @PathParam for your id and one "normal" parameter to get your request data.

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

I hope this helps.

我希望这有帮助。

回答by carbontrans

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

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

As per the code sample of method putTodo of class TodoResource , your code should be like this.

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

@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 will solve your problem.

希望这能解决您的问题。

Cheers

干杯

回答by rahul pasricha

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 try @PUT instead of @Post as well. Hope this helps

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

回答by diego matos - keke

I had the same problem I solved in 3 Stepswith Hymansonin Netbeans/Glashfish btw.

顺便说一句,我在 Netbeans/Glashfish 中与Hymanson 的3 步中解决了同样的问题。

1)Requirements :

1)要求:

some of the Jars I used :

我使用的一些罐子:

 commons-codec-1.10.jar
 commons-logging-1.2.jar
 log4j-1.2.17.jar
 httpcore-4.4.4.jar
 Hymanson-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
 Hymanson-jaxrs-json-provider-2.6.4.jar
 Hymanson-databind-2.7.0-rc1.jar
 Hymanson-annotations-2.7.0-rc1.jar
 Hymanson-core-2.7.0-rc1.jar

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

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

2)Java Class where you send your Post. First ,Convert with Hymanson the Entity User to Json and then send it to your Rest Class.

2)您发送帖子的Java类。首先,将实体用户 Hymanson 转换为 Json,然后将其发送到您的 Rest Class。

import com.fasterxml.Hymanson.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 Hymanson 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 receive the Entity JPA/Hibernate . Here with your MediaType.APPLICATION_JSON you recieve the Entity in this way :

3)Java Class Rest,您希望在其中接收实体 JPA/Hibernate 。在这里,您使用 MediaType.APPLICATION_JSON 以这种方式接收实体:

""id":99,"usuarioPadre":null,"nickname":null,"clave":null,"nombre":null,"apellidos":null,"isLoginWeb":null,"isLoginMovil":null,"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}"

""id": 99,"usuarioPadre":null,"nickname":null,"clave":null,"nombre":null,"apellidos":null,"isLoginWeb":null,"isLoginMovil":null," estado":null,"correoElectronico":null,"imagePerfil":null,"perfil":null,"urlCambioClave":null,"telefono":null,"cellular":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 problem with running the web after using this code may be because of the @Consumes in XML... you must set it as @Consumes(MediaType.APPLICATION_JSON)

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

回答by Anil kumar

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