仅接收json Android 4.0时出错
我从Android设备连接到Webservice,然后发送参数并获取json。 当我用android API测试时,它还可以<4.0 ex2.3.3 当我用另一个设备测试时,它的api是4.0.3,4.0.4 那么我就不能接收json了 这是我的密码仅接收json Android 4.0时出错,android,json,web-services,Android,Json,Web Services,我从Android设备连接到Webservice,然后发送参数并获取json。 当我用android API测试时,它还可以
json = getJson("http://search.twitter.com/search.json?result_type=recent&rpp=3&q=iphone");
private String getJson(String uri) {
String json = null;
try {
URL url = new URL(uri);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
Log.d(TAG,"1");
// conn.setConnectTimeout(10 * 1000); //6s
if (conn.getResponseCode() == 200) {
// get successfull
// read Json
Log.d(TAG,"2");
BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
int len = 0;
byte[] buf = new byte[1024];
StringBuffer stringBuffer = new StringBuffer();
while ((len = in.read(buf)) != -1) {
String s = new String(buf, 0, len);
stringBuffer.append(s);
}
Log.d(TAG,"3");
json = stringBuffer.toString();
Log.d(TAG,json);
}
} catch (Exception e) {
Log.e(TAG, "error get json :" + e.toString());
json = null;
}
return json;
}
错误
11-20 19:42:22.555: E/TEST(29097): error get json :android.os.NetworkOnMainThreadException
它适用于您的2.3.3,因为自API11以来,它就一直在android中运行 您需要将使用
HTTP
连接的部分移动到另一个线程,或者更好地使用
私有类下载文件任务扩展异步任务{
受保护的长doInBackground(URL…URL){
int count=url.length;
长totalSize=0;
for(int i=0;i
它适用于您的2.3.3,因为自API11以来,它就一直在android中运行
您需要将使用HTTP
连接的部分移动到另一个线程,或者更好地使用
私有类下载文件任务扩展异步任务{
受保护的长doInBackground(URL…URL){
int count=url.length;
长totalSize=0;
for(int i=0;i
从Asynctask调用Web服务。问题将得到解决。从Asynctask调用Web服务。这个问题会解决的
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}