简体   繁体   中英

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.

@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?


Note: I'm asking about Spring with the aim to investigate the facilities provided by the framework. I well know that it is possible to do that by defining manually the request body.

Cheers, 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.

In the client application, it would look like this :

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. RESTeasy will search for the webservice matching with with your client (according to the path and the request type) and will create a connection.

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

Hope this was helpfull.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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