简体   繁体   English

消费将JSON对象作为请求主体传递的RESTful WebService

[英]Consuming a RESTful WebService passing a JSON object as request body

I've defined a RESTful WebService (by using RESTEasy on JBoss AS 7 ) that consumes a JSON data stream. 我已经定义了一个RESTful WebService (通过在JBoss AS 7上使用RESTEasy )来使用JSON数据流。

@PUT
@Path("/send")
@Consumes(MediaType.APPLICATION_JSON)
public Response consumeJSON(Student student) {
    String output = student.toString();
    // Do something...
    return Response.status(200).entity(output).build();
}

How can I call my WS from another Spring -based webapp, by properly using the RestTemplate , mapping a Java Object to JSON and passing it as request body? 如何通过正确使用RestTemplate ,将Java对象映射到JSON并将其作为请求主体传递,从另一个基于Spring的Web应用程序中调用WS?


Note: I'm asking about Spring with the aim to investigate the facilities provided by the framework. 注意:我问的是Spring,目的是研究框架提供的功能。 I well know that it is possible to do that by defining manually the request body. 我很清楚,可以通过手动定义请求主体来做到这一点。

Cheers, V. V干杯

In the client application, you can create an interface with the same signature as the one you expose on the server side, and the same path. 在客户端应用程序中,您可以创建一个接口,该接口具有与在服务器端公开的接口相同的签名,并且具有相同的路径。 Then, in the spring configuration file, you can use the RESTeasy client API to generate a proxy connecting to the exposed webservice. 然后,在spring配置文件中,可以使用RESTeasy客户端API生成连接到公开Web服务的代理。

In the client application, it would look like this : 在客户端应用程序中,它将如下所示:

SimpleClient.java SimpleClient.java

@PUT
@Path("/send")
@Consumes(MediaType.APPLICATION_JSON)
public Response consumeJSON(Student student);

Config.java 配置文件

@Bean
public SimpleClient getSimpleClient(){
    Client client = ClientFactory.newClient();
    WebTarget target = client.target("http://example.com/base/uri");
    ResteasyWebTarget rtarget = (ResteasyWebTarget)target;

    SimpleClient simple = rtarget.proxy(SimpleClient.class);

    return simple;
}

Then, in the place where you want to invoke this web service, you inject it with Spring and you can call the method. 然后,在要调用此Web服务的地方,用Spring注入它,然后可以调用该方法。 RESTeasy will search for the webservice matching with with your client (according to the path and the request type) and will create a connection. RESTeasy将搜索与您的客户端匹配的Web服务(根据路径和请求类型),并创建一个连接。

Launcher.java Launcher.java

@Resource
private SimpleClient simpleClient;

public void sendMessage(Student student) {
    simpleClient.consumeJSON(student);
}

Docs on the RESTesay client API : http://docs.jboss.org/resteasy/docs/3.0.7.Final/userguide/html/RESTEasy_Client_Framework.html RESTesay客户端API上的文档: http ://docs.jboss.org/resteasy/docs/3.0.7.Final/userguide/html/RESTEasy_Client_Framework.html

Hope this was helpfull. 希望这对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM