我剛開始研究Retrofit庫,所以真的要求一點幫助。我試圖從響應中獲取數據,但我只能鏈接到對象。改造:試圖從響應中獲得結果
interface IApi {
@GET("api")
Call<PostModel> getData();
}
/*---------------------------------------------------------------------*/
public class App extends Application {
private static IApi siteApi;
@Override
public void onCreate() {
super.onCreate();
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://yesno.wtf/")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
siteApi = retrofit.create(IApi.class);
}
public static IApi getApi() {
return siteApi;
}
}
/*------------------------------------------------------------------------*/
class PostModel {
@SerializedName("answer")
@Expose
private String answer;
@SerializedName("forced")
@Expose
private Boolean forced;
@SerializedName("image")
@Expose
private String image;
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
public Boolean getForced() {
return forced;
}
public void setForced(Boolean forced) {
this.forced = forced;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
/*------------------------------------------------------------------------*/
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
App.getApi().getData().enqueue(new Callback<PostModel>() {
@Override
public void onResponse(Call<PostModel> call, Response<PostModel> response) {
Log.e("Response", response.body().toString());
}
@Override
public void onFailure(Call<PostModel> call, Throwable t) {
t.printStackTrace();
Toast.makeText(MainActivity.this, "An error occurred during networking", Toast.LENGTH_SHORT).show();
}
});
}
}
我想,有一些變量類型的問題,但我不知道...我會很感激任何幫助。
UPD: 我的logcat:
...
d/OkHttp { 「答案」: 「沒有」, 「強迫」:假的, 「形象」: 「https://yesno.wtf/assets/no/27-8befe9bcaeb66f865dd3ecdcf8821f51.gif」 }
d/OkHttp:< - END HTTP(108字節體)
E /響應:[email protected]
所以問題是我如何能得到我的迴應的身體? (「答案」:「沒有」,「強迫」:假的,「形象」:「https://yesno.wtf/assets/no/27-8befe9bcaeb66f865dd3ecdcf8821f51.gif」)
你所說的 '鏈接對象' 呢? 'response.body()'中沒有值? – RadekJ
可否請您指定問題以及logcat –
您的問題是什麼?你可以發佈日誌貓 –