【问题标题】:REST API - GET Method with input parameter as JAVA Object in bodyREST API - 将输入参数作为正文中的 JAVA 对象的 GET 方法
【发布时间】:2017-08-21 14:41:55
【问题描述】:

这是我目前的 REST GET 方法。

@GET
@Path("/URI/{input1}")
@Produces(MediaType.APPLICATION_JSON)
public List<T> getDetails(@PathParam("input1") String input1) throws ServiceException;

现在我想再添加 3 个输入参数。我可以创建一个包含所有 4 个输入参数的 POJO 对象并将该 POJO 传递给 GET 方法,而不是添加所有 4 个参数作为路径参数

@GET
@Path("/URI")
@Produces(MediaType.APPLICATION_JSON)
public List<T> getDetails(InputPojo input) throws ServiceException;

带有输入参数的POJO类:

class InputPojo {
    String input1;
    String input2;
    String input3;
    // Getters and Setters.
}

或者这是否违反 REST GET 规范,我不能使用 Java POJO 对象作为输入参数?

【问题讨论】:

    标签: java rest api get specifications


    【解决方案1】:

    根据GET方法的HTTP协议规范不能提供正文。例如。您只能将数据作为 URI 的一部分传递。

    实际上,您可以通过 GET 方法提供对象。只需将其转换为文本(如 JSON),将其编码为 base64(因为 URI 中不允许使用空格等符号),将该内容放入input1 路径变量(例如/URI/encodedpojohere)。然后在服务器上解码input1字符串并转换回Java的POJO。

    这种方法有几个限制(其中最明显的是 URI 字符串的长度有限 - 大约 65535 个符号)。并且效率低下(您不能传输任意字节序列并且需要对其进行编码)。也许,这就是为什么没有任何标准的转换器/注释/帮助类来通过 GET 请求传输 POJO 的原因。因此,请改用 POSTPUT 方法。 Spring 和其他框架为它们提供了一堆实用程序类/注解。


    通常,可以在 HTTP GET 方法中提供正文。那里讨论了这种方法:HTTP GET with request body。一些知名产品,例如Elasticsearch 提供这样的查询:

    GET /bank/_search
    {
      "query": { "match_all": {} }
    }
    

    (对应的HTTP请求可以通过curl命令行工具执行)

    无论如何,带有正文的 HTTP GET 是非标准的。也许,这就是 Java 不支持它的原因。

    【讨论】:

      【解决方案2】:
      @Path("/injectdemo")
      

      公共类TestClass {

      //URI: http:URI/injectdemo/create?queryparam={"input1" : "XYZ", "input2" : "ABC", "input3" : "DEF"}
      @GET
      @Consumes(MediaType.APPLICATION_JSON)
      @Produces(MediaType.APPLICATION_JSON)
      @Path("/create")
      public InputPojo postMsg(@QueryParam("queryparam") String jsonString) throws JsonParseException, JsonMappingException, IOException {
      
          //Method 1: Convert Json String to required pojo
          InputPojo inputPojo = new ObjectMapper().readValue(jsonString, InputPojo.class);
      
          //Method 2: Convert Json String to required pojo
          InputPojo inputPojo1 =new Gson().fromJson(jsonString, InputPojo.class);
      
      
          return inputPojo;
      }
      

      }

      JSON 字符串可以在 URI 中发送为:http:URI/injectdemo/create?queryparam={"input1" : "XYZ", "input2" : "ABC", "input3" : "DEF"}。它对我有用。但这不是一个好习惯,因为如果 Pojo 是健康的(即变量太多),Uri 会太长。

      【讨论】:

        猜你喜欢
        • 2021-11-08
        • 1970-01-01
        • 2014-12-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多