Problem statement:
我试图访问一个REST API,它将使用Volley返回各种HTTP状态代码(400,403,200等)的JSON对象 .
对于200以外的任何HTTP状态,似乎“意外响应代码400”是一个问题 . 有没有人有办法绕过这个'错误'?
Code:
protected void getLogin() {
final String mURL = "https://somesite.com/api/login";
EditText username = (EditText) findViewById(R.id.username);
EditText password = (EditText) findViewById(R.id.password);
// Post params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("username", username.getText().toString());
params.put("password", password.getText().toString());
JsonObjectRequest req = new JsonObjectRequest(mURL, new JSONObject(
params), new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONObject obj = response
.getJSONObject("some_json_obj");
Log.w("myApp",
"status code..." + obj.getString("name"));
// VolleyLog.v("Response:%n %s", response.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.w("error in response", "Error: " + error.getMessage());
}
});
// add the request object to the queue to be executed
AppController.getInstance().addToRequestQueue(req);
}
8 回答
我所做的是在我的网址上添加一个额外的'/',例如:
至
在不更改
Volley
源代码的情况下执行此操作的一种方法是检查VolleyError
中的响应数据并自行解析 .从f605da3 commit开始,
Volley
会抛出包含原始网络响应的ServerError exception .因此,您可以在错误侦听器中执行与此类似的操作:
对于将来,如果
Volley
发生更改,可以按照上述方法进行操作,您需要检查服务器发送的原始数据VolleyError
并进行解析 .我希望他们实现source file中提到的
TODO
.您需要将Content-Type添加到 Headers 中 .
我也得到了相同的错误,但在我的情况下,我用空格调用 url .
然后,我通过解析如下修复它 .
试试这个 ...
你的意思是想获得状态代码?
VolleyError
的成员变量类型为NetworkResponse
,它是公共的 .您可以访问
error.networkResponse.statusCode
以获取http错误代码 .我希望它对你有所帮助 .
在我的情况下,我没有写入reg_url:8080 . String reg_url =“http://192.168.29.163:8080/register.php”;
只是为了更新所有,经过一些审议后,我决定使用Async Http Client来解决我之前的问题 . 该库允许更清晰的方法(对我来说)操纵HTTP响应,尤其是在所有场景/ HTTP状态中返回JSON对象的情况下 .