简体   繁体   English

Android Volley自定义请求

[英]Android volley custom request

I have implemented a custom request using volley in order to login to a webserver. 我已经使用Volley实现了自定义请求,以便登录到Web服务器。

This is the function im using: 这是即时通讯使用的功能:

private void volleyTest2(String username, String password, String deviceid) {

    Map<String, String> params;
    params = new HashMap<>();

    params.put("username", username);
    params.put("password", password);
    //params.put("device_id", deviceid);
    params.put("device_id", "H767A76S7D6D");

    Volley.newRequestQueue(MainActivity.this).add(
        new CustomJsonRequest(Request.Method.POST, URL, params,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    String output="";
                    // Parsing json
                    for (int i = 0; i < response.length(); i++) {
                        try {

                            JSONObject obj = response.getJSONObject(i);
                            output+=obj.getString("name") + " "+ obj.getString("surname");

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                    Toast.makeText(getApplicationContext(), "Benvenuto, " + output, Toast.LENGTH_LONG).show();
                    showProgress(false);
                }
            }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d("Error: " + error.getMessage());
                        Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
                        showProgress(false);
                    }
                }

        )

        {
            @Override
            protected Response parseNetworkResponse(NetworkResponse response) {
                try {

                    String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
                    return Response.success(new JSONArray(jsonString), HttpHeaderParser.parseCacheHeaders(response));

                } catch (UnsupportedEncodingException e) {
                    return Response.error(new ParseError(e));
                } catch (JSONException je) {
                    return Response.error(new ParseError(je));
                }
            }

        }

    );

}

And this is my CustomJsonRequest: 这是我的CustomJsonRequest:

public class CustomJsonRequest extends Request {

Map<String, String> params;
private Response.Listener listener;

public CustomJsonRequest(int requestMethod, String url, Map<String, String> params, Response.Listener responseListener, Response.ErrorListener errorListener) {
    super(requestMethod, url, errorListener);
    this.params = params;
    this.listener = responseListener;
}

@Override
protected void deliverResponse(Object response) {
    listener.onResponse(response);
}

@Override
public Map<String, String> getParams() throws AuthFailureError {
    return params;
}

@Override
protected Response parseNetworkResponse(NetworkResponse response) {
    try {
        String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
        return Response.success(new JSONObject(jsonString), HttpHeaderParser.parseCacheHeaders(response));
    } catch (UnsupportedEncodingException e) {
        return Response.error(new ParseError(e));
    } catch (JSONException je) {
        return Response.error(new ParseError(je));
    }
}

} }

Since i can not edit the php side this is the scenario: - if the login is correct i receive a JSONArray - if the login ain't correct i receive a JSONObject like this: My only issue is that if the login is incorrect i receive this error: Error: org.json.JSONException: Value {"error":"Username\\/password non trovati"} of type org.json.JSONObject cannot be converted to JSONArray 由于我无法编辑PHP端,因此是这种情况:-如果登录正确,我会收到JSONArray-如果登录不正确,我会收到这样的JSONObject:我唯一的问题是,如果登录不正确,我会收到此错误: Error: org.json.JSONException: Value {"error":"Username\\/password non trovati"} of type org.json.JSONObject cannot be converted to JSONArray

So how can I handle the incorrect login if I get a JSONObject instead of a JSONArray ? 那么,如果我得到JSONObject而不是JSONArray,该如何处理错误的登录? I'd like to show only the content inside the Object, so: "Username\\/password non trovati" 我只想显示对象内部的内容,因此: "Username\\/password non trovati"

UPDATE1: UPDATE1:

    private void volleyTest2(String username, String password, String deviceid) {

    Map<String, String> params;
    params = new HashMap<>();

    params.put("username", username);
    params.put("password", password);
    //params.put("device_id", deviceid);
    params.put("device_id", "H767A76S7D6D");

    Volley.newRequestQueue(MainActivity.this).add(
        new CustomJsonRequest(Request.Method.POST, URL, params,
            new Response.Listener<JsonElement>() {
                @Override
                public void onResponse(JsonElement element) {
                    String output="";
                    // Parsing json

                    if(element.isJsonArray()){
                        JsonArray array=element.getAsJsonArray();
                        //read response here
                        Log.d(TAG,"array.toString(): " + array.toString());

                    }else if(element.isJsonObject()){
                        JsonObject object=element.getAsJsonObject();
                        //read response here
                        Log.d(TAG,"object.toString(): " + object.toString());

                    }


                    Toast.makeText(getApplicationContext(), "Benvenuto, " + output, Toast.LENGTH_LONG).show();
                    showProgress(false);
                }
            }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d("Error: " + error.getMessage());
                        Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
                        showProgress(false);
                    }
                }

        )

        {
            @Override
            protected Response parseNetworkResponse(NetworkResponse response) {
                try {

                    String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
                    return Response.success(new JSONArray(jsonString), HttpHeaderParser.parseCacheHeaders(response));

                } catch (UnsupportedEncodingException e) {
                    return Response.error(new ParseError(e));
                } catch (JSONException je) {
                    return Response.error(new ParseError(je));
                }
            }

        }

    );

}

Possiblities Possiblities
1. Make request return type as com.google.gson.JsonElement.class and check like this 1.将请求返回类型设置为com.google.gson.JsonElement.class并进行如下检查

        @Override
        public void onResponse(JsonElement element) {
            if(element.isJsonArray()){
                JsonArray array=element.getAsJsonArray();
                //read response here
            }else if(element.isJsonObject()){
                JsonObject object=element.getAsJsonObject();
                //read response here
            }
        }

2. Make String request try to convert it JSONArray or JSONObject . 2.使String请求尝试将其转换为JSONArrayJSONObject while converting catch those exceptions if occurred ( JSONException : JSONObject cannot be converted to JSONArray) . 转换时捕获这些异常(如果发生) (JSONException:JSONObject无法转换为JSONArray)

3 . 3 Make StringRequest and parse response to JsonElement and check whether its JsonObject or JsonArray 进行StringRequest并解析对JsonElement响应,并检查其JsonObject还是JsonArray

        @Override
        public void onResponse(String s) {
            JsonParser parser = new JsonParser();
            JsonElement element = parser.parse(s);

            if (element.isJsonArray()) {
                JsonArray array = element.getAsJsonArray();
                //read response here
            } else if (element.isJsonObject()) {
                JsonObject object = element.getAsJsonObject();
                //read response here
            }

        }

4. Best way : Change server code :) 4.最佳方法:更改服务器代码:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM