我已使用volley实现了一个自定义请求,以便登录网络服务器。
这是我正在使用的功能:
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));
}
}
}
);
}
这是我的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));
}
}
}
由于我无法编辑php端,这就是场景:
- 如果登录正确,我会收到JSONArray
- 如果登录不正确,我会收到这样的JSONObject:
我唯一的问题是如果登录不正确我收到此错误:
Error: org.json.JSONException: Value {"error":"Username\/password non trovati"} of type org.json.JSONObject cannot be converted to JSONArray
那么如果我得到一个JSONObject而不是JSONArray,我怎么能处理错误的登录?
我只想显示对象内的内容,所以:"Username\/password non trovati"
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));
}
}
}
);
}
答案 0 :(得分:0)
Possiblities
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请求尝试将其转换为JSONArray
或JSONObject
。转换时捕获那些异常,如果发生(JSONException:JSONObject无法转换为JSONArray)。
第3 即可。制作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. 最佳方式:更改服务器代码:)