【问题标题】:Consuming a RESTful WebService passing a JSON object as request body使用将 JSON 对象作为请求主体传递的 RESTful WebService
【发布时间】:2014-07-03 00:46:51
【问题描述】:

我已经定义了一个 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();
}

如何正确使用 RestTemplate,将 Java 对象映射到 JSON 并将其作为请求正文传递,从另一个基于 Spring 的 web 应用程序调用我的 WS?


注意:我询问 Spring 是为了调查框架提供的设施。我很清楚可以通过手动定义请求正文来做到这一点。

干杯,V。

【问题讨论】:

    标签: java json spring web-services rest


    【解决方案1】:

    在客户端应用程序中,您可以创建一个与您在服务器端公开的签名相同且路径相同的接口。 然后,在spring配置文件中,可以使用RESTeasy客户端API生成代理连接到暴露的webservice。

    在客户端应用程序中,它看起来像这样:

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

    然后,在你想调用这个web服务的地方,用Spring注入它,你就可以调用这个方法了。 RESTeasy 将搜索与您的客户端匹配的 Web 服务(根据路径和请求类型)并创建连接。

    Launcher.java

    @Resource
    private SimpleClient simpleClient;
    
    public void sendMessage(Student student) {
        simpleClient.consumeJSON(student);
    }
    

    有关 RESTesay 客户端 API 的文档:http://docs.jboss.org/resteasy/docs/3.0.7.Final/userguide/html/RESTEasy_Client_Framework.html

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-24
      • 2019-09-15
      相关资源
      最近更新 更多