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

cle*_*ake 22 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);
}
Run Code Online (Sandbox Code Playgroud)

lis*_*oss 39

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

从此开始f605da3 commit,Volley抛出包含原始网络响应的ServerError异常.

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

/* 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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

对于将来,如果Volley更改,可以按照上述方法,您需要检查VolleyError服务器发送的原始数据并解析它.

我希望他们实现源文件TODO提到的.


Tay*_*eer 15

@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;
}
Run Code Online (Sandbox Code Playgroud)

您需要将Content-Type添加到标题中.


dhi*_*iku 9

试试这个 ...

 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;
    }
Run Code Online (Sandbox Code Playgroud)


Ras*_*med 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) {
                                ...
                                ...
                                ...
Run Code Online (Sandbox Code Playgroud)