【问题标题】:Design for REST API clientREST API 客户端设计
【发布时间】:2017-08-11 16:56:30
【问题描述】:

我想创建一个 REST API 客户端,它对于同一个 REST API 服务器将调用不同的 URL。这种不同的调用将向客户端返回 JSON 和 XML。 什么是适合这种情况的好的设计模式?

到目前为止,我已经想出了策略和命令的组合:

public interface IRestCall {
    /** Setup the URL for the call. */
    void setup(IRestSetup setup) throws Exception;
    /** Execute the call, using the URL set up in the first step. 
     * @throws Exception */
    void call() throws Exception;
    /** Process the result and return to the user. */
    <T> T getResult(IRestResultProcessor<T> result) throws Exception;
} 

这是策略界面。该战略的背景将 在 Facade 类的某些 Get/Post/Put 方法中。

IRestSetup 和 IRestResultProcessor 是 Command 对象的接口 这将为 REST API 设置 URL 并处理结果。

【问题讨论】:

  • 在服务器端解析 JSON 的好设计是使用 GSON。 journaldev.com/2321/gson-example-tutorial-parse-json 您必须设计适当的 JavaBean 来解析和验证 JSON 响应。对于 XML,您可以使用 JAXB 绑定。
  • 感谢您的回答,但这只是我问题的一小部分。另外,我对设计感兴趣,而不是特定的框架。

标签: java rest design-patterns


【解决方案1】:

我认为您不需要一些特殊的设计模式来处理这种情况。我个人只会为 GET 和 POST 请求添加一些通用方法。下面的代码只处理 GET 请求,但应该足以理解我的意思。

您处理 GET 请求的客户端方法可能类似于

/**
restUrl - url to the service 
resClz - the actual POJO object that the JSON or XML response will be mapped to
resType - type of MIME object returned by the server (typically MediaType.APPLICATION_JSON or MediaType.APPLICATION_XML)
*/  
  <T> T doRestGet(String restUrl, Class<T> resClz, String resType){

        T obj;
        Client client = ClientBuilder.newClient();            

        WebTarget target = client.target(UriBuilder.fromUri("http://localhost:8088/Your_WS_root").build()); 

        try{

         obj =(T) target.path(restUrl).request()
              .accept(resType).get().readEntity(resClz);


        }catch(Exception e){
         System.out.println(e);//log or propagate the exception

        return null;
        }
        return obj;
}

您的服务器方法可能类似于

@GET
  @Path("/userMsg")
  @Produces(MediaType.APPLICATION_JSON)
  public UserMessage getUsersOne() {

   UserMessage uMsg = new UserMessage();
   uMsg.setUserMsg("successful call");
   return uMsg;
  }

现在你会调用你的服务

UserMessage uMsg = (UserMessage)doRestGet("userMsg", UserMessage.class, MediaType.APPLICATION_JSON ); 

【讨论】:

  • 哪个框架最适合实现这个?
  • 嗯,Jersey 是 JAX-RS 规范的参考实现,它可能是最容易使用的 REST 框架(至少对我而言)
猜你喜欢
  • 2022-12-11
  • 2018-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
  • 2013-08-30
  • 2019-11-25
相关资源
最近更新 更多