首页 > 解决方案 > 为什么改造忽略成功的响应代码?

问题描述

我是在 Android 上使用 Restful API 的新手,我正在使用 Retrofit 将我的 API 连接到我的 Android 应用程序,我想做的是将用户信息插入到我的 PostgreSQL 数据库中,但是每次我插入新数据时,我的应用程序尽管成功插入并返回代码 200,但忽略 onResponse 方法并直接转到 onFailure,我该如何解决这个问题?

我使用 HttpLoggingInterceptor 记录错误,但它显示代码 200,这意味着从服务器端一切正常。

改造服务类(UserService)

public interface UserService {
    //Return list of users
    @GET("/users")
    Call<List<User>> getUsers();
    //Post new user
    @POST("/users")
    Call<User> postUser(@Body User user);
}

用户类

public class User {

    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("email")
    @Expose
    private String email;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

}

改造连接和 HttpLogging 实例

HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BASIC);
        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

        httpClient.addInterceptor(logging);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .client(httpClient.build())
                .build();

在 MainActivity 上触发插入的 FAB

FloatingActionButton fab = findViewById(R.id.fab);
        final User user = new User();
        user.setName("Michael");
        user.setEmail("michael@example.com");
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                userService.postUser(user).enqueue(new Callback<User>() {
                    @Override
                    public void onResponse(Call<User> call, Response<User> response) {
                        if(response.isSuccessful()) {
                            Toast.makeText(MainActivity.this, "User successfully inserted", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<User> call, Throwable t) {
                        Toast.makeText(MainActivity.this, "Error inserting into database", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });

标签: androidapiretrofit

解决方案


可能是因为转换器抛出了异常。在 onFailure 方法中打印可抛出的错误消息。如果只是您的转换器与线路上的数据之间存在分歧,那么这就是需要解决的应用程序问题。

参考这个了解更多

https://github.com/square/retrofit/issues/1446

看到截图后更新

这是一个解析错误。作为响应,它需要一个用户类型的 JSON 对象,但当前响应正在返回 JSON 字符串。


推荐阅读