我在Android Studio中使用Retrofit 2.2,这是我的类ServerTime:
public class ServerTime {
@SerializedName("time")
private String time;
@SerializedName("date")
private String date;
@SerializedName("milliseconds_since_epoch")
private String milliSeconds;
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getMilliSeconds() {
return milliSeconds;
}
public void setMilliSeconds(String milliSeconds) {
this.milliSeconds = milliSeconds;
}
}
我的界面:
public interface Api {
@GET("/")
public Call<ServerTime> getServerTime();
}
我的方法是:
void fetchTime2() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://luisbaltodano.pe.hu/Galeria/Time.php/")
.addConverterFactory(GsonConverterFactory.create())
.build();
Api api = retrofit.create(Api.class);
Call<ServerTime> serverTimeCall = api.getServerTime();
serverTimeCall.enqueue(new Callback<ServerTime>() {
@Override
public void onResponse(Call<ServerTime> call, Response<ServerTime> response) {
ServerTime serverTime = response.body();
tvNombre.setText("Date: " + serverTime.getDate());
tvCelular.setText("Time: " + serverTime.getTime());
}
@Override
public void onFailure(Call<ServerTime> call, Throwable t) {
Toast.makeText(getApplicationContext(), "Error while fetching time", Toast.LENGTH_SHORT).show();
}
});
}
当我跑步时,只在onFailure方法中显示Toast。
现在,当我更改BaseUrl:
时 .baseUrl("http://date.jsontest.com/")
这项工作非常完美......
请帮帮我:( ..查看网址:
答案 0 :(得分:0)
您应该更改后端部分:http://luisbaltodano.pe.hu/Galeria/Time.php/应该返回带有下一个标题的json内容:Content-Type:application/json;
。现在它返回text/html
。