Android开发:调用JSON数据出错


开发的项目在2.3 2.1的手机上可以调到JSON数据 到4.0的手机上无法获取数据

开发的版本是2.1的 最小2.1的

   
  /**
  
* @author frankiewei. Json封装的工具类.
*/
public class JSONUtil {

private static String RootUrl = "http://app.wishgift.cn/";
private static String AppUrl = RootUrl
+ "?format=json";
private static final String TAG = "JSONUtil";

/**
* 获取json内容
*
* @param url
* @return JSONArray
* @throws JSONException
* @throws ConnectionException
*/
public static JSONObject getJSON(String url) throws JSONException,
Exception {
url = AppUrl+url;
return new JSONObject(getRequest(url));
}

/**
* 向api发送get请求,返回从后台取得的信息。
*
* @param url
* @return String
*/
protected static String getRequest(String url) throws Exception {
return getRequest(url, new DefaultHttpClient(new BasicHttpParams()));
}

/**
* 向api发送get请求,返回从后台取得的信息。
*
* @param url
* @param client
* @return String
*/
protected static String getRequest(String url, DefaultHttpClient client)
throws Exception {
String result = null;
int statusCode = 0;
HttpGet getMethod = new HttpGet(url);
Log.d(TAG, "do the getRequest,url=" + url + "");
try {
// getMethod.setHeader("User-Agent", USER_AGENT);

HttpResponse httpResponse = client.execute(getMethod);
// statusCode == 200 正常
statusCode = httpResponse.getStatusLine().getStatusCode();
Log.d(TAG, "statuscode = " + statusCode);
// 处理返回的httpResponse信息
result = retrieveInputStream(httpResponse.getEntity());
Log.d(TAG, "json = " + result);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
throw new Exception(e);
} finally {
getMethod.abort();
}
return result;
}

/**
* 处理httpResponse信息,返回String
*
* @param httpEntity
* @return String
*/
protected static String retrieveInputStream(HttpEntity httpEntity) {

int length = (int) httpEntity.getContentLength();
// the number of bytes of the content, or a negative number if unknown.
// If the content length is known but exceeds Long.MAX_VALUE, a negative
// number is returned.
// length==-1,下面这句报错,println needs a message
if (length < 0)
length = 10000;
StringBuffer stringBuffer = new StringBuffer(length);
try {
InputStreamReader inputStreamReader = new InputStreamReader(
httpEntity.getContent(), HTTP.UTF_8);
char buffer[] = new char[length];
int count;
while ((count = inputStreamReader.read(buffer, 0, length - 1)) > 0) {
stringBuffer.append(buffer, 0, count);
}
} catch (UnsupportedEncodingException e) {
Log.e(TAG, e.getMessage());
} catch (IllegalStateException e) {
Log.e(TAG, e.getMessage());
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
return stringBuffer.toString();
}
}

2.1 logcat

请输入图片描述

4.0 logcat

请输入图片描述

请输入图片描述

Android json

天衣无缝D亡霊 11 years, 10 months ago

我们好像也遇到过这个问题。

4.0下的json库和以前的json库不同,应该是遇到了特殊字符导致解析出现问题。

可以先打印出来,再逐个排除下。

另外回收数据的代码建议用

   
  HttpEntity entity = httpResponse.getEntity();
  
response = EntityUtils.toString(entity, HTTP.UTF_8);

不需要自己处理InputStream了。

黑猫即是正义 answered 11 years, 10 months ago

Your Answer