我正在学习如何在GSON中使用Retrofit库,这样我就可以让我的未来应用程序更加稳定。但是,我期待“奇怪的错误”。 我从https://www.metaweather.com/api/location/search/?query=san获取位置(用于测试目的)
这是我的代码
MainActivity
public class MainActivity extends AppCompatActivity {
private SOService mService;
private long currentTime; //start time
private long finishedTime; //end time
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mService = ApiUtils.getClient();
currentTime = System.currentTimeMillis();
mService.getLocations().enqueue(new Callback<List<LocationsList>>() {
@Override
public void onResponse(Call<List<LocationsList>> call, Response<List<LocationsList>> response) {
if(response.isSuccessful()){
Log.d("TAG", response.body().toString());
finishedTime = System.currentTimeMillis();
Log.d("TAG", "It took " + TimeUnit.MILLISECONDS.toSeconds(finishedTime - currentTime) + " seconds to complete");
}
else{
Log.d("TAG","Code"+response.code());
}
}
@Override
public void onFailure(Call<List<LocationsList>> call, Throwable t) {
Log.d("TAG",t.getMessage());
}
});
}
}
ApiUtils
public class ApiUtils {
private static final String BASE_URL="https://www.metaweather.com/";
public static SOService getClient(){
return RetrofitClient.getClient(BASE_URL).create(SOService.class);
}
}
RetrofitClient
public class RetrofitClient {
private static Retrofit client;
public static Retrofit getClient(String baseUrl){
if(client == null){
client = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return client;
}
}
SOService
public interface SOService {
@GET("/api/location/search/?query=san")
Call<List<LocationsList>> getLocations();
}
我删除了包和导入以获得更干净的代码。 LocationList是POJO。执行代码时,我收到以下消息: 09-25 16:23:12.913 10994-10994 / pw.davor.www.retrofit D / TAG:[LocationsList {title ='San Francisco'....
09-25 16:23:12.913 10994-10994 / pw.davor.www.retrofit D / TAG:完成需要10秒钟
但是,当我在Postman中执行GET请求时,大约需要100-300ms。