Intereting Posts

发布JSON到NodeJS服务器显示成功时,它实际上是一个失败

这是我的android代码发布到我的nodejs服务器

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!!"); } }); 

当我触发上述代码时,即使服务器返回响应状态400(如下所示)(从日志中),我也会在控制台中打印出“ Success

 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 

当我改变System.out.println("Success!!");System.out.println(response.toString()); 我在控制台中得到以下内容:

 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} 

所以它检测到错误,但不执行onFailure内的代码,

当onFailure被执行? 或者我在这里做错了什么?

Solutions Collecting From Web of "发布JSON到NodeJS服务器显示成功时,它实际上是一个失败"

  System.out.println(response.toString()); // wrong way 

要将java对象转换为JSON格式,请使用toJson()方法。

  System.out.println(""+new Gson().toJson(response));