如何解析凌空的401响应数据,这是服务器响应我得到了使用凌空网络响应,但它无法获得JSON格式的响应数据
Status 200 OK
{
alert: {
title: "Unauthorised access to appointment"
message: ""
}-
response: "0"
}
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Req Failed!");
mProgressDialog.dismiss();
NetworkResponse localNetworkResponse = error.networkResponse;
if (localNetworkResponse != null) {
if (!WebAPIEngine.checkStatusCodeVolley(localNetworkResponse.statusCode)) {
AlertDialogUtil.displayErrorAlert(error.toString(), mContext);
}
} else {
Log.e(TAG, error.toString());
try {
JSONObject jsonObject = new JSONObject(error.getMessage());
if (WebAPIEngine.processErrorAlertResp(jsonObject)) {
AlertDialogUtil.displayErrorAlert(WebAPIEngine.getErrorMessage(), mContext);
} else {
AlertDialogUtil.displayErrorAlert(error.toString(), mContext);
}
}
catch (Exception e) { e.printStackTrace(); }
}
}
});
答案 0 :(得分:1)
您可以使用以下代码获取回复
String responseString="";
if (networkResponse != null) {
try {
Log.v(TAG , ".getResponseError code :"+networkResponse.statusCode);
responseString = new String(networkResponse.data, HttpHeaderParser.parseCharset(networkResponse.headers));
Log.v(TAG, ".getResponseError body :" + responseString);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
此外,谨防401错误在Volley中无法处理:The SO answer完美地解释了它。
答案 1 :(得分:1)
正如vedant1811提到的那样, 401错误在Volley中无法处理,但我最近发现The S.O answer中未提及的解决方法,我认为如果提供的话可能会有用解决方案不适合您的情况。
1)创建扩展任何排球请求的基本请求(StringRequest,JSONObjectRequest等等)并覆盖 parseNetworkError() 功能
/* Custom volley request. I chose to extend JsonObjectRequest
* feel free to extend any other volley class
*/
public class CundinasRequest extends JsonObjectRequest{
...
@Override
//This will make the volley error message to contain your server's error message
protected VolleyError parseNetworkError(VolleyError volleyError) {
if(volleyError.networkResponse != null && volleyError.networkResponse.data != null){
volleyError = new VolleyError(new String(volleyError.networkResponse.data));
}
return volleyError;
}
...
}
2)在 onErrorResponse() 实现中,您只需解析服务器的错误。这是一个例子:
//Volley request is made somewhere in this activity
public class MainActivity extends Activity {
private final String AUTH_ERROR_IDENTIFIER = "invalid_token";
...
public isAuthorizationError(VolleyError error){
return error.getMessage().contains(AUTH_ERROR_IDENTIFIER);
}
@Override
public void onErrorResponse(VolleyError error) {
if(isAuthorizationError(error)
Log.e(TAG, "Please log in again");
}
}
我发现此解决方法很有用,因为我无法更改服务器的返回状态,并且授权错误始终相同。为了给你一个想法,它看起来像这样:
{
"error": "invalid_token",
"error_description": "Invalid access token: AN INVALID TOKEN"
}