当我尝试将HTTP POST响应转换为JSONArray时,我收到错误:
org.json.JSONException:java.lang.String类型的值无法转换为JSONArray
错误发生在行中: JSONArray jArray = new JSONArray(result);
字符串结果的值是[{“return”:“1”}],但它在开头包含一个额外的空白字符,当删除时,解决问题。但是,此字符不是空白,因为修剪不能解决问题。我相信POST响应存在一些问题,可能构造不当? (或者POST请求可能是错的?)欢迎任何帮助。
GET请求工作得很好,但我需要做一个POST请求。
这是代码:
HttpPost("usuarioLogin.php",nameValuePairs);
String result = ConvertResponseToString();
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
ret = json_data.getInt("return");
retorno = (ret==1)?true:false;
}
}
catch(JSONException e1){
e1.printStackTrace();
} catch (ParseException e1) {
e1.printStackTrace();
}
这是函数HttpPost()
的代码private void HttpPost(String php, ArrayList<NameValuePair> nameValuePairs)
{
try{
HttpClient httpclient = new DefaultHttpClient();
String host = com.android.taggies.LoginUser.getContext().getResources().getString(R.string.host);
HttpPost httppost = new HttpPost("http://"+host+php);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
}
这是函数ConvertResponseToString()
的代码private String ConvertResponseToString()
{
//convert response to string
String result = null;
try{
//BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
return result;
}
这是我回复POST的php的代码
<?php
mysql_connect("localhost","root","");
mysql_select_db("dbTaggies");
$q=mysql_query("SELECT count(*) as 'return' FROM users
WHERE name='$_POST[user]' AND password ='$_POST[pass]'");
while($e=mysql_fetch_assoc($q))
{
$output[]=$e;
}
print(json_encode($output));
mysql_close();
?>
答案 0 :(得分:1)
我正在使用这个,对我来说总是很好用:
DefaultHttpClient client = new DefaultHttpClient();
JSONObject json = null;
String resoult = "";
try
{
HttpPost postRequest = new HttpPost("XXXXXXXXXXXXXXXXXX");
HttpResponse postResponse = client.execute(postRequest);
HttpEntity postResponseEntity = postResponse.getEntity();
if (postResponseEntity != null)
resoult= EntityUtils.toString(postResponseEntity);
json = new JSONObject(resoult);
}
catch(Exception e)
{
}
答案 1 :(得分:0)
问题解决了。
PHP文件以UTF-8 WITH BOM保存,解决方案是以UTF8保存文件,没有BOM,并且删除了POST响应中的初始字符。