[英]Retrofit 2 returns null body
我正在嘗試實施Retrofits展示的基本練習:對github API進行簡單的get查詢。 我正在嘗試獲取存儲庫列表,但是盡管結果的狀態為200,但正文為空。 github上有一些票證抱怨同樣的問題,看起來好像來自json轉換器。 我用gson。 但是我沒發現是哪個代碼的罪魁禍首...
這是我的依賴項:
dependencies {
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
存儲庫POJO:
public class Repository {
private int id;
private String name;
private String full_name;
private String html_url;
// getters + setters + toString
}
客戶端界面:
public interface GithubClient {
public static final String ENDPOINT = "https://api.github.com";
@GET("/users/{user}/repos")
Call<List<Repository>> getByUser(@Path("user") String user);
@GET("/search/repositories")
Call<List<Repository>> getByKeywords(@Query("q") String q);
}
如何初始化:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(GithubClient.ENDPOINT)
.addConverterFactory(GsonConverterFactory.create())
.build();
githubClient = retrofit.create(GithubClient.class);
並執行請求:
Call<List<Repository>> request = githubClient.getByUser(inputText);
request.enqueue(new Callback<List<Repository>>() {
@Override
public void onResponse(Call<List<Repository>> call, Response<List<Repository>> response) {
progress.setVisibility(View.GONE);
results.setText(response.toString());
}
@Override
public void onFailure(Call<List<Repository>> call, Throwable t) {
progress.setVisibility(View.GONE);
results.setText(t.getMessage());
}
});
我在瀏覽器中訪問了https://api.github.com/search/repositories?q=threetenabp ,並且看到的JSON結構與您期望的不同:
{ "total_count": 4, "incomplete_results": false, "items": [ { "id": 38503932, "name": "ThreeTenABP", ... }, { "id": 61799973, "name": "ThreeTenABPSample", ... }, { "id": 78114982, "name": "TwitterPack", ... }, { "id": 76958361, "name": "ZonedDateTimeProguardBug", ... } ] }
在您的代碼中,我看到了這個調用:
@GET("/search/repositories")
Call<List<Repository>> getByKeywords(@Query("q") String q);
如果接收到的JSON響應的結構如下,這將起作用:
[
{ "id": ... },
{ "id": ... }
]
換句話說,在實際的JSON響應中, "items"
字段就是您所說的List<Repository>
,但是您需要一些東西來表示頂級響應對象。
我將創建一個像這樣的新類:
public class GithubResponse {
private int total_count;
private boolean incomplete_results;
private List<Repository> items;
}
然后,我將您客戶端界面中的調用更改為:
@GET("/search/repositories")
Call<GithubResponse> getByKeywords(@Query("q") String q);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.