Sunday, 7 May 2017

Posting JSON to NodeJS server shows success when it is actually a failure

Here is my android code to post to my nodejs server

registrationjson.setUsername(username.getText().toString());
registrationjson.setPassword(password.getText().toString());

                    Gson gson = new Gson();
                    String jsonfromForm = gson.toJson(registrationjson);

                    client = new OkHttpClient();
                    RequestBody body = RequestBody.create(JSON, jsonfromForm);
                    Request request = new Request.Builder()
                            .url(uri)
                            .post(body)
                            .addHeader("content-type", "application/json; charset=utf-8")
                            .build();

                    client.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            System.out.println("Failure!!");
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            System.out.println("Success!!");
                        }
                    });

When I trigger the above code, I get Success printed out in the console even though the server returns respond status of 400 as it is shown below (from the logs) :

2017-05-08T06:03:36.358142+00:00 app[web.1]: Request Received:  5/8/2017 6:3:36
2017-05-08T06:03:36.358391+00:00 app[web.1]: Registration Request Received:  5/8/2017 6:3:36
2017-05-08T06:03:36.370211+00:00 app[web.1]: POST /users/register 400 8.328 ms - 11

and when I change System.out.println("Success!!"); to System.out.println(response.toString()); I get the following printed in the console:

D/NetworkSecurityConfig: No Network Security Config specified, using platform default
05-08 10:10:20.005 4325-4632/ I/System.out: Response{protocol=http/1.1, code=400, message=Bad Request, url=URL}

so it detects the error but it doesn't execute the code inside onFailure,

when onFailure is executed? or what am I doing wrong here?



via Behrouz Riahi

No comments:

Post a Comment