读书人

【新人】关于访问网络存储的有关问题

发布时间: 2013-09-14 13:03:22 作者: rapoo

【新人求助】关于访问网络存储的问题
package com.web.test;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.util.ByteArrayBuffer;
import org.apache.http.util.EncodingUtils;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HelloWeb extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

TextView tv = new TextView(this);
String myString = null;

try {
URL uri = new URL("http://www.baidupcs.com/file/1cb251ec0d568de6a929b520c4aed8d1?xcode=8b8eddcff9b768b0fe3b5383d02719e1682db0a8df3ab0c0&fid=2987144212-250528-3553184730&time=1379061716&sign=FDTAXER-DCb740ccc5511e5e8fedcff06b081203-IajFP7ZTY8WIHqM2f7Ao%2BQKeNbQ%3D&to=wb&fm=N,B,M,mn&expires=8h&rt=sh&r=128013118&logid=2936171168&sh=1&fn=test.txt");

URLConnection ucon = uri.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(100);
int current = 0;
while((current = bis.read()) != -1) {


baf.append((byte)current);
}

myString = new String(baf.toByteArray(), "GBK");
} catch(Exception e) {
myString = e.getMessage();
}

tv.setText(myString);
this.setContentView(tv);
}
}

求大神看一下哪里出问题了?在真机上测试总会抛出异常。
[解决办法]
网络操作要在一个新线程里做,不能放在UI主线程,否则会导致UI反应慢或者ANR。
4.0以后强制要求这么做,否则会报android.os.NetworkOnMainThreadException。

读书人网 >Android

热点推荐