【问题标题】:Setting object in http get request在 http get 请求中设置对象
【发布时间】:2015-07-22 15:07:34
【问题描述】:

我正在为 Pageable Spring 数据资源编写客户端 java 程序 存储库 GET API 的格式为:

public Page<Person> findByCountry(..., Pageable pageable);

我创建了格式的可分页请求

Pageable pageable = new PageRequest(1, 40, new Sort("name"));

但是,我想知道如何将这个可分页设置到我的http client。 我正在使用HttpGetHttpPost

我用谷歌搜索了一下,发现大多数链接都使用弹簧休息控制器。我不能通过使用 apache http 客户端来做到这一点吗? Springs hatoas 似乎是另一种选择。但这意味着向我的客户项目添加另一个 jar。只是如何在请求上设置有效负载的问题吗?

此外,如果有更好的方法,请告诉我。我想遍历所有页面,直到数据用完。

谢谢。

【问题讨论】:

    标签: java spring spring-data http-get apache-commons-httpclient


    【解决方案1】:

    我不确定我要建议的方法是否是最好的方法,但这就是我的做法。由于您无法在精益客户端中引用 Spring 依赖对象,即 Pageable 而不向您的客户端添加 Spring 依赖项,您可能希望将 PageRequest 详细信息作为 HTTP GET 查询参数发送到您的 HTTP GET API,类似这样并循环您的与技术无关的 pagewrapper 结果如下所示。

    API 签名

    public PageWrapper findByCountry(..., int page, int size, String sortBy, String sortDirection);

    PageWrapper:

    List<T> items;
    int currentPage;
    int totalPages;
    int totalItems;
    boolean isLast;
    

    API 代码:

    Pageable nextPageable = new PageRequest(page, size, new Sort(sortBy));
    Page<Person> personsPage =  countryService.findByCountry(.., nextPageable);
    if(null != personsPage){
      PageWrapper<Person> pageWrapper = new PageWrapper<>();
      pageWrapper.setItems(personsPage.getContent());
      pageWrapper.setTotalPages(personsPage.getTotalPages());
      pageWrapper.setTotalItems(personsPage.getTotalElements());
      pageWrapper.setCurrentPage(personsPage.getNumber())
      pageWrapper.setIsLast(personsPage.isLast());
      return pageWrapper
    }
    

    客户端代码:

    PageWrapper page = null;
    do {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("page", index++);
        paramMap.put("size", size);
        paramMap.put("sortBy", "name");
        page = (PageWrapper) httpClient.get(requestURI, paramMap);
        process(page);
    }while(!page.getIsLast())
    

    【讨论】:

      【解决方案2】:

      结果证明解决方案很简单。 我犯的错误是使用非默认名称设置参数。如果您传递正确的参数,Spring 的 rest api 将创建一个可分页对象(如 reference doc for Spring Data Repositories 的 'HandlerMethodArgumentResolvers for Pageable and Sort' 部分所述)

      如果请求具有给定名称的参数(如页面、大小等),则会自动创建可分页。

      【讨论】:

        猜你喜欢
        • 2012-10-03
        • 2014-08-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-13
        • 2012-01-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多