Java Android检查服务器是否响应;是";JSON
如您所知,如果查询不成功,phpJava Android检查服务器是否响应;是";JSON,java,php,javascript,android,json,Java,Php,Javascript,Android,Json,如您所知,如果查询不成功,phpmysql\u query()请求将返回false。随着时间的推移,我养成了一个习惯(如果这是一个坏习惯,你应该告诉我) $res = mysql_query(...); if($res == false){ echo json_encode("notOK"); }else{ $return = array(); // process query result into that array echo json_encode($r
mysql\u query()
请求将返回false
。随着时间的推移,我养成了一个习惯(如果这是一个坏习惯,你应该告诉我)
$res = mysql_query(...);
if($res == false){
echo json_encode("notOK");
}else{
$return = array();
// process query result into that array
echo json_encode($return);
}
// (...)
success : function(response){
var res = JSON.parse(resonse);
if(res == "notOK"){
// error handling
}else{
// proceed
}
}
// (...)
响应的处理在JavaScript中运行良好,方法如下
$res = mysql_query(...);
if($res == false){
echo json_encode("notOK");
}else{
$return = array();
// process query result into that array
echo json_encode($return);
}
// (...)
success : function(response){
var res = JSON.parse(resonse);
if(res == "notOK"){
// error handling
}else{
// proceed
}
}
// (...)
然而,在安卓系统中,这似乎不起作用。我处理服务器请求的标准过程是
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse response;
Vector<JSONObject> vector = new Vector<JSONObject>();
try{
response = client.execute(get);
HttpEntity entity = response.getEntity();
if(entity != null){
InputStream in = entity.getContent();
String result = convertStreamtoString(in);
JSONArray resultArray = new JSONArray(result);
int len = resultArray.length();
for(int i=0; i<len; i++){
vector.add(resultArray.getJSONObject(i));
}
in.close();
}
} catch (//...
有没有一种类似Javascript的处理方法?我是不是做错了什么
PS:我在这里找到了,但我不认为它是重复的,因为这里是关于检查对象是否“熟悉JSON”好的,问题是有时返回的数据表示JSON对象,有时它表示JSON数组。您的Android代码在所有情况下都将数据作为数组处理。您可以处理这个问题,但不能使用您现在使用的JSON.org库。由于您是为Android开发的,因此您内置了对Gson库的访问权限,使用它您可以做到:
JSONElement jsonElem = new JsonParser().parse(result);
if(jsonElem.isJsonArray()) {
// Normal data
} else {
// 'Error' data'
}
很简单。但是请注意,您确实应该使用适当的HTTP状态代码(50x代码之一)来指示错误情况,而不是仅仅依赖返回的数据。根据:
is应该是“application/json”
布尔值isJSON=“application/json”.equalsIgnoreCase(entity.getContentType()) 您需要为该特定错误添加
catch
语句。没有catch的try
在Java中没有任何作用(据我所知)。如果您发布您要返回的实际json,它也会很有帮助。看起来它只是“真的”,显然不能转换成数组。@Dave当然我在做错误处理,刚刚编辑了我的问题@Sam Dufel确实如此,但是如何像在JS中那样处理这个问题(我知道有一个var
在声明时没有特定的类型)。@ValentinoRu:为什么不在尝试创建JSONArray
之前使用if(“notOK.equals(result))
?OP在这两种情况下都发送JSON。