簡體   English   中英

使用Retrofit2的響應主體為空

[英]Response body empty using Retrofit2

因此,我在Postman中嘗試了該請求,並且效果很好。 但是,當我在Android中執行該操作時,response.body()為空。 該請求將發送電子郵件和密碼以進行登錄,並且應返回User對象以及其他詳細信息。

loginUser.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                if (response.isSuccessful()) {
                   loginView.onLoginResult(response.body());
                } else {
                    loginView.showLoginErrorResult();
                }
            }

這是我的改造界面:

public interface NetworkAPI {

   @POST("/login")
   Call<User> login(@Body UserLogin userLogin);
}

RetrofitClient:

public class RetrofitClient {

private static Retrofit retrofit = null;

public static Retrofit getAPI(String BASE_URL) {


    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(logging).build();

    if (retrofit == null) {
        retrofit = new Retrofit
                .Builder()
                .baseUrl(BASE_URL)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit;
}

}

我的用戶類別:

public class User {

@SerializedName("id")
@Expose
private String id;

@SerializedName("token")
@Expose
private String token;

@SerializedName("email")
@Expose
private String email;

@SerializedName("firstName")
@Expose
private String firstName;

@SerializedName("lastName")
@Expose
private String lastName;

public User(String id, String token, String email, String firstName, String lastName) {
    this.id = id;
    this.token = token;
    this.email = email;
    this.firstName = firstName;
    this.lastName = lastName;
}
   //getters &setters...
}

郵遞員要求:

{
    "email":"test@email.com",
    "password":"123456"
}

郵遞員回應:

{
    "success": true,
    "payload": {
        "email": "test@email.com",
        "firstName": "test",
        "lastName": "test",
    }
}

我也收到200回應,但身上沒有資料

像這樣創建一個新模型

public class ResponseApi{
        boolean success;
        User payload;

        public boolean isSuccess() {
            return success;
        }

        public void setSuccess(boolean success) {
            this.success = success;
        }

        public User getPayload() {
            return payload;
        }

        public void setPayload(User payload) {
            this.payload = payload;
        }

    }

然后像這樣更改代碼

public interface NetworkAPI {

   @POST("users/login")
   Call< ResponseApi > login(@Body UserLogin userLogin);
}

希望它能工作。由於結構不同,翻新實際上無法解析您的json對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM