如何从 github 搜索 api 中获取所有结果?
How get all results from github search api?
我需要使用 github 搜索 api 和分页来获取所有结果。现在我使用请求:
https://api.github.com/search/repositories?q=lib&page=1&per_page=20
我读到回复还包括 Link header,其中包含到下一页的 ready-made URL。作为回应,我有 link https://api.github.com/search/repositories?q=lib&page=2&per_page=20>
和 link 到最后一页:https://api.github.com/search/repositories?q=java&page=50&per_page=20
但是我不明白如何使用这些 links 实现到下一页的转换。
您可以创建一个变量来跟踪当前页面。并在每次成功时增加它,直到您的列表大小等于 total_count
.
on RecyclerView
end reached 方法可以再次调用。
我已尝试演示以下示例,请使用您正在使用的实际调用和内容。只是了解模式。
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();
}
};
}
}
我需要使用 github 搜索 api 和分页来获取所有结果。现在我使用请求:
https://api.github.com/search/repositories?q=lib&page=1&per_page=20
我读到回复还包括 Link header,其中包含到下一页的 ready-made URL。作为回应,我有 link https://api.github.com/search/repositories?q=lib&page=2&per_page=20>
和 link 到最后一页:https://api.github.com/search/repositories?q=java&page=50&per_page=20
但是我不明白如何使用这些 links 实现到下一页的转换。
您可以创建一个变量来跟踪当前页面。并在每次成功时增加它,直到您的列表大小等于 total_count
.
on RecyclerView
end reached 方法可以再次调用。
我已尝试演示以下示例,请使用您正在使用的实际调用和内容。只是了解模式。
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();
}
};
}
}