【发布时间】:2017-11-22 22:17:38
【问题描述】:
我已经实现了 Retrofit 从服务返回一些数据,但是大小为 0,在 getGamesData 函数中它不会进入回调方法。
我不确定我声明 BASE_URL 的方式是否正确,以及 ApiInterface 方法 GET 是否正确。
根本不调用 OnResponse 和 OnFailure 方法。
请推荐
返回数据的 URL。
https://dl.dropboxusercontent.com/s/abcd/gameData
它会返回一个像这样的 JSON。
{
"response": "success",
"currency" : "GBP",
"data" : [
{
"name": "Game 1",
"jackpot": 34000000,
"date": "2015-01-25T20:20:30+01:00"
},
{
"name": "Game 2",
"jackpot": 100000000,
"date": "2015-02-16T08:40:30+01:00"
},
{
"name": "Game 3",
"jackpot": 100000,
"date": "2015-11-09T10:25:30+01:00"
},
{
"name": "Game 4",
"jackpot": 45000000,
"date": "2015-03-10T18:55:30+01:00"
},
{
"name": "Game 5",
"jackpot": 60000000,
"date": "2015-07-20T03:45:30+01:00"
},
{
"name": "Game 6",
"jackpot": 95000000,
"date": "2015-06-22T09:40:30+01:00"
},
{
"name": "Game 7",
"jackpot": 100000000,
"date": "2015-10-19T08:30:30+01:00"
},
{
"name": "Game 8",
"jackpot": 12000,
"date": "2015-12-06T07:20:30+01:00"
}
]
}
ApiClient
public class ApiClient {
public static final String BASE_URL = "https://dl.dropboxusercontent.com/s/abcd/";
public static Retrofit retrofit = null;
public static Retrofit getApiClient()
{
if(retrofit == null)
{
retrofit = new Retrofit.Builder().baseUrl(BASE_URL).
addConverterFactory(GsonConverterFactory.create()).build();
}
return retrofit;
}
}
ApiInterface - 更新
public interface ApiInterface {
@GET("/gameData")
Call<GamesWebOrbEntity> getGamesData();
}
ApiCalls - 更新
public class ApiCalls implements IApiCalls{
private ApiInterface apiInterface;
private GamesWebOrbEntity gamesEntities;
@Override
public GamesWebOrbEntity getGamesData() {
apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
Call<GamesWebOrbEntity> call = apiInterface.getGamesData();
try{
call.enqueue(new Callback<GamesWebOrbEntity>() {
@Override
public void onResponse(Call<GamesWebOrbEntity> call, Response<GamesWebOrbEntity> response) {
gamesEntities = response.body();
}
@Override
public void onFailure(Call<GamesWebOrbEntity> call, Throwable t) {
String test = "Failure";
}
});
}catch (Exception e){
System.out.println("Error " + e.getMessage());
}
return gamesEntities;
}
}
IApiCalls - 更新
public interface IApiCalls {
GamesWebOrbEntity getGamesData();
}
GamesWebOrbEntity _ 已更新
public class GamesWebOrbEntity {
@SerializedName("response")
private String response;
@SerializedName("currency")
private String currency;
@SerializedName("data")
private List<GameEntity> gameEntities;
}
游戏实体
public class GameEntity {
private String name;
private Integer jackpot;
private Date date;
}
使用它
List<GamesWebOrbEntity> gamesEntity = apiCalls.getGamesData();
谢谢 回复
【问题讨论】:
标签: android retrofit retrofit2