Android截击-BasicNetwork.performRequest:意外响应代码400

Android截击-BasicNetwork.performRequest:意外响应代码400,android,android-volley,Android,Android Volley,问题陈述: 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

问题陈述:

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);
}
我正在尝试访问一个RESTAPI,该API将使用Volley为各种HTTP状态代码(400403200等)返回一个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);
}
受保护的void getLogin(){
最终字符串mURL=”https://somesite.com/api/login";
EditText用户名=(EditText)findViewById(R.id.username);
EditText密码=(EditText)findViewById(R.id.password);
//将要发送到服务器的Post参数
HashMap params=新的HashMap();
put(“username”,username.getText().toString());
put(“password”,password.getText().toString());
JsonObjectRequest req=新JsonObjectRequest(mURL,新JSONObject(
params),新的Response.Listener(){
@凌驾
公共void onResponse(JSONObject响应){
试一试{
JSONObject obj=响应
.getJSONObject(“some_json_obj”);
Log.w(“myApp”,
“状态代码…”+obj.getString(“名称”);
//VolleyLog.v(“响应:%n%s”,响应.toString(4));
}捕获(JSONException e){
e、 printStackTrace();
}
}
},new Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
w(“响应错误”,“错误:+error.getMessage());
}
});
//将请求对象添加到要执行的队列中
AppController.getInstance().addToRequestQueue(req);
}

你的意思是想获取状态码

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

您可以访问http错误代码的
error.networkResponse.statusCode

我希望这对你有帮助。

试试这个

 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;
    }
StringRequest sr=new-StringRequest(类型、url、new-Response.Listener()){
@凌驾
公共void onResponse(字符串响应){
//有效响应
}
},new Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
//错误
}
}){
@凌驾
受保护的映射getParams(){
Map params=新的HashMap();
参数put(“用户名”,用户名);
参数put(“密码”,密码);
参数put(“授权类型”、“密码”);
返回参数;
}
@凌驾
公共映射getHeaders()引发AuthFailureError{
Map params=新的HashMap();
//如果不需要或使用application/json,请删除此行
//参数put(“内容类型”、“应用程序/x-www-form-urlencoded”);
返回参数;
}
@覆盖
公共映射getHeaders()引发AuthFailureError{
HashMap headers=新的HashMap();
headers.put(“内容类型”、“应用程序/json;字符集=utf-8”);
返回标题;
}

您需要将内容类型添加到标题。

为了更新所有内容,经过仔细考虑后,我决定使用异步Http客户端来解决我之前的问题。该库允许(对我来说)更干净的方法来操作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();
            }
        }
    });
}

不更改
Volley
源代码的一种方法是检查
VolleyError
中的响应数据并自行解析

截至,
Volley
抛出包含原始网络响应的

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

/* 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
中服务器发送的原始数据并对其进行解析


我希望他们实现中提到的
TODO

在我的例子中,我没有用8080编写reg\u url。
String reg_url=“”;

我也遇到了同样的错误,但在我的例子中,我是用空格调用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) {
                                ...
                                ...
                                ...
String url=“您的url链接”;
url=url.replaceAll(“,“%20”);
StringRequest StringRequest=新的StringRequest(Request.Method.GET,url,
新建com.android.volley.Response.Listener(){
@凌驾
公共void onResponse(字符串响应){
...
...
...

我所做的是在我的url中附加一个额外的“/”,例如:

改变

公共静态最终字符串URL=“”

公共静态最终字符串URL=“”


这是因为我正在使用000webhostapp应用程序发送get请求。api工作正常,但正在获取基本网络。性能请求:意外响应代码500。@HemsLodha 500-内部服务器错误“遇到意外情况时发出的一般错误消息,没有更具体的消息适用”服务器上出现问题。遇到类似错误,但我的错误是“意外响应代码415”。我的内容类型为application/json,但添加charset=utf-8后,问题消失了。我的字符为“é”在我的查询字符串中。在我对所有参数进行编码后工作。那么这是什么解决方案非常感谢!!这在Android 4.4.2中解决了我的问题。这是一个很好的答案。在新版本中,代码工作正常,但在旧版本中,这让我成为了一个巨大的过山车驱动器。没想到基于Linux/Unix的Android不是t请早点处理。谢谢@ RasooMuHaMeD,你应该考虑选择<代码> ListBoos作为正确的答案。这是你的问题的答案,因此有理由。
String url = "http://www.google.com" 
String url = "http://www.google.com/"