【问题标题】:How get all results from github search api?如何从 github search api 获取所有结果?
【发布时间】:2021-08-23 07:41:53
【问题描述】:

我需要使用带有分页功能的 github search api 获取所有结果。现在我使用请求: https://api.github.com/search/repositories?q=lib&page=1&per_page=20 我读到响应还包括 Link 标头,其中包含指向下一页的现成 URL。作为回应,我有链接 https://api.github.com/search/repositories?q=lib&page=2&per_page=20> 并链接到最后一页:https://api.github.com/search/repositories?q=java&page=50&per_page=20 但我不明白如何使用这些链接实现到下一页的转换。

【问题讨论】:

    标签: java android github-api


    【解决方案1】:

    您可以创建一个变量来跟踪当前页面。 & 每次成功都会增加它,直到您的列表大小等于 total_count。

    在RecyclerView end达到的方法可以再次调用。

    我已尝试演示以下示例,请使用您正在使用的实际调用和内容。只需了解模式即可。

    public class MainActivity extends AppCompatActivity {
    
        private int page = 1;
    
        private ArrayList<Object> items = new ArrayList<>();
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            call();
        }
        
        //dummy call
        private void call(){
            String url = "https://api.github.com/search/repositories?q=lib&page=" + page + "&per_page=20";
            //pass the new url with page to call or just params as per your need
            new ResponseListener(url){
                @Override
                public void onSuccess(ArrayList<Object> list,Integer totalCount) {
                    //parse & add items
                    items.addAll(list);
                    //check if you have items same as total count.
                    // If true then it means you've reached the end
                    if (items.size() < totalCount){
                        //increase the page number for next call
                        page++;
                    }
                }
    
                @Override
                public void onError(Exception e) {
                    e.printStackTrace();
                }
            };
        }
    
    
    }
    

    【讨论】:

    • 要删除大量 HTTPS 调用(这会减慢你的程序和 GitHub 也不喜欢),只需将 per_page 增加到 100 之类的值(或最大值是什么) ) - 编辑:在输入999999 后查看结果后,看起来 GitHub 最多只返回 100 个结果,所以使用超过 20 个。
    猜你喜欢
    • 1970-01-01
    • 2016-07-31
    • 2018-08-31
    • 2020-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-27
    • 1970-01-01
    相关资源
    最近更新 更多