Android 将JSON发布到NodeJS服务器显示成功,但实际上失败了
这是我要发布到nodejs服务器的android代码Android 将JSON发布到NodeJS服务器显示成功,但实际上失败了,android,node.js,android-studio,okhttp3,okhttp,Android,Node.js,Android Studio,Okhttp3,Okhttp,这是我要发布到nodejs服务器的android代码 registrationjson.setUsername(username.getText().toString()); registrationjson.setPassword(password.getText().toString()); Gson gson = new Gson(); String jsonfromForm = gson.toJson(re
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
,如下所示(从日志中):
当我更改System.out.println(“Success!!”)时
toSystem.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
Do
要将java对象转换为JSON格式,请使用toJson()
方法
System.out.println(""+new Gson().toJson(response));
我明白了,但这不是我问题的答案,不管怎样,它打印出混乱的JSON,数百个单词以I/System.out开头:{“body”:{“headers”:{“namesAndValues”:[“Server”,“Cowboy”,“Connection”,“keep-alive”,“X-Powered-By”,“Express”
,@BehrouzRiahi它打印出乱七八糟的JSON,以“GSON onResponse method”开头的数百个单词获取整个JSON。@BehrouzRiahi你想要什么?我的onFailure方法没有执行,即使响应状态代码是400。为什么?@BehrouzRiahi尝试使用?如果(response.code()=400)
?
System.out.println(""+new Gson().toJson(response));