如何使用 Volley 获取错误消息说明
2022-09-03 03:40:45
我正在使用Volley库从Android Java向c#后端发送http请求。后端应用程序按预期使用错误代码和描述以及状态描述进行响应。我可以通过wireshark看到响应状态描述,但不知道如何在Android端获取描述字符串。
final JsonObjectRequest request = new JsonObjectRequest(JsonObjectRequest.Method.POST,
url,json,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
TextView mTextView = (TextView) findViewById(R.id.output);
print("Success");
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
TextView mTextView = (TextView) findViewById(R.id.output);
print("Failure (" + error.networkResponse.statusCode + ")");
//Trying to get the error description/response phrase here
}
}
);
这是处理请求的 C# 代码:
[WebInvoke(Method = “POST”, UriTemplate = “users”, BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)][OperationContract] void addUser(String username, String firstname, String lastname, String email, String hash) { Console.WriteLine(DateTime.Now + “ Packet receieved”);
//Stores the response object that will be sent back to the android client
OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;
String description = "User added";
response.StatusCode = System.Net.HttpStatusCode.OK;
//Tries to add the new user
try
{
userTable.Insert(username,firstname,lastname,email,hash);
}
catch (SqlException e)
{
//Default response is a conflict
response.StatusCode = System.Net.HttpStatusCode.Conflict;
description = "Bad Request (" + e.Message + ")";
//Check what the conflict is
if (userTable.GetData().AsEnumerable().Any(row => username == row.Field<String>("username")))
{
description = "Username in use";
}
else if (userTable.GetData().AsEnumerable().Any(row => email == row.Field<String>("email")))
{
description = "Email address in use";
}
else
{
response.StatusCode = System.Net.HttpStatusCode.BadRequest;
}
}
//display and respond with the description
Console.WriteLine(description);
response.StatusDescription = description;
}
我浏览了其他人的问题,但似乎找不到我正在寻找的答案。有人知道如何做到这一点吗?我尝试过的许多方法都会导致空的大括号,表示带有空正文的 JSON。我正在专门尝试获取状态描述。