发布JSON来的NodeJS服务器显示成功时,它实际上是一个失败
问题描述:
这是我的Android代码张贴到我的NodeJS服务器发布JSON来的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!!");
}
});
当我触发上面的代码,我得到Success
在控制台打印出连虽然服务器返回响应的400状态,因为它是如下所示(从原木):和
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处时?或者我在这里做错了什么?
答
不要
System.out.println(response.toString()); // wrong way
做
到Java对象转换为JSON格式,请使用toJson()
方法。
System.out.println(""+new Gson().toJson(response));
我给你,但它不是我的问题的答案,反正它打印出与以'I/System.out的几百字的凌乱JSON:{“体”:{“头”:{” namesAndValues“:[”Server“,”Cowboy“,”Connection“,”keep-alive“,”X-Powered-By“,”Express“, –
@BehrouzRiahi它打印出乱七八糟的JSON, GSON onResponse方法提取整个JSON。 –
@BehrouzRiahi你想要什么? –