Android Volley - BasicNetwork.performRequest:意外的响应代码400

时间:2014-11-07 08:20:09

标签: android android-volley

问题陈述:

我正在尝试访问一个REST API,它将使用Volley返回各种HTTP状态代码(400,403,200等)的JSON对象。

对于200以外的任何HTTP状态,似乎“意外响应代码400”是个问题。有没有人有办法绕过这个'错误'?

代码:

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);
}

9 个答案:

答案 0 :(得分:38)

在不更改Volley源代码的情况下执行此操作的一种方法是检查VolleyError中的响应数据并自行解析。

f605da3 commit起,Volley会抛出包含原始网络响应的ServerError exception

因此,您可以在错误监听器中执行与此类似的操作:

/* import com.android.volley.toolbox.HttpHeaderParser; */
public void onErrorResponse(VolleyError error) {

    // As of f605da3 the following should work
    NetworkResponse response = error.networkResponse;
    if (error instanceof ServerError && response != null) {
        try {
            String res = new String(response.data,
                       HttpHeaderParser.parseCharset(response.headers, "utf-8"));
            // Now you can use any deserializer to make sense of data
            JSONObject obj = new JSONObject(res);
        } catch (UnsupportedEncodingException e1) {
            // Couldn't properly decode data to string
            e1.printStackTrace();
        } catch (JSONException e2) {
            // returned data is not JSONObject?
            e2.printStackTrace();
        }
    }
}

将来,如果Volley发生变化,可以按照上述方法检查服务器发送的原始数据VolleyError并解析它。

我希望他们实施source file中提到的TODO

答案 1 :(得分:13)

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
    HashMap<String, String> headers = new HashMap<String, String>();
    headers.put("Content-Type", "application/json; charset=utf-8");
    return headers;
}

您需要在标题中添加Content-Type。

答案 2 :(得分:9)

我也遇到了同样的错误,但在我的情况下,我用空格调用 url

然后,我通过解析如下修复它。

String url = "Your URL Link";

url = url.replaceAll(" ", "%20");

StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                            new com.android.volley.Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                ...
                                ...
                                ...

答案 3 :(得分:7)

试试这个......

 StringRequest sr = new StringRequest(type,url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

            // valid response
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            // error
        }
    }){

@Override
    protected Map<String,String> getParams(){
        Map<String,String> params = new HashMap<String, String>();
            params.put("username", username);
            params.put("password", password);
            params.put("grant_type", "password");
        return params;
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String,String> params = new HashMap<String, String>();
        // Removed this line if you dont need it or Use application/json
        // params.put("Content-Type", "application/x-www-form-urlencoded");
        return params;
    }

答案 4 :(得分:2)

您的意思是想获取状态代码吗?

VolleyError的成员变量类型为NetworkResponse,并且是公开的。

您可以访问error.networkResponse.statusCode以获取http错误代码。

我希望它对你有所帮助。

答案 5 :(得分:1)

在我的情况下,我没有写入reg_url:8080。 字符串reg_url =“http://192.168.29.163:8080/register.php”;

答案 6 :(得分:0)

只是为了更新所有内容,经过一番商议后,我决定使用Async Http Client来解决我之前的问题。该库允许更清晰的方法( to my )来操纵HTTP响应,尤其是在所有场景/ HTTP状态中都返回JSON对象的情况下。

protected void getLogin() {

    EditText username = (EditText) findViewById(R.id.username); 
    EditText password = (EditText) findViewById(R.id.password); 

    RequestParams params = new RequestParams();
    params.put("username", username.getText().toString());
    params.put("password", password.getText().toString());

    RestClient.post(getHost() + "api/v1/auth/login", params,
            new JsonHttpResponseHandler() {

        @Override
        public void onSuccess(int statusCode, Header[] headers,
                JSONObject response) {

            try {

                //process JSONObject obj 
                Log.w("myapp","success status code..." + statusCode);

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers,
                Throwable throwable, JSONObject errorResponse) {
            Log.w("myapp", "failure status code..." + statusCode);


            try {
                //process JSONObject obj
                Log.w("myapp", "error ..."  + errorResponse.getString("message").toString());
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });
}

答案 7 :(得分:0)

我所做的是追加额外的&#39; /&#39;到我的网址,例如

String url = "http://www.google.com" 

String url = "http://www.google.com/"

答案 8 :(得分:0)

更改

  

公共静态最终字符串URL =“ http://api-Location”;

  

公共静态最终字符串URL =“ https://api-Location

这是因为我正在使用000webhostapp应用