简体   繁体   中英

Retrofit - knowing when the POST is unsuccessful

I am using retrofit to @POST a new User object to my server. The username is a unique key in the database table. If I execute an asynchronous call with a unique username, the entry is added to the User table. The response is successful.

However if I try to execute the call for a User with an existing username, the entry is not added to the database table (as expected) BUT the response is successful. In all cases I am getting successful response.

How can I notify/check that the operation was successful? If the create/update/delete calls are successfully reflected on the database?

endpoint:

@POST("user")
Call<User> saveUser(@Body User m);

Sample call:

call.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {

                try {
                    if(response.isSuccessful()) {

                        Log.i(Constants.LOG, response.raw().toString());
                    }
                } catch (Exception e) {
                    Log.e(Constants.LOG, e.toString());
                }
            }

The raw response output in all scenarios:

Response{protocol=http/1.1, code=200, message=OK, url=http://myapi.com/user}

ok so I finally found out how to resolve this. In my rest api I had to call the status and send the custom code :

res.status(300).send({ error: 'Something went wrong' });

In the case of adding a duplicate User, the response is unsuccessful and I get the raw output:

Response{protocol=http/1.1, code=300, message=Internal Server Error, url=http:///myapi.com/user}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM