我正在尝试访问一个网站,并将html源代码放入TextView.我的模拟器上的浏览器有效,但我认为在我的应用程序中访问互联网无法正常运行.我想我可能不得不使用AsyncTask,但我不知道如何正确实现它,或者我甚至不得不使用它.我对编程非常陌生,并且已经在这个网站上看了一段时间,但似乎无法弄明白.
这是主要代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView httpTest = (TextView) findViewById(R.id.textView1);
GetTest sourceCode = new GetTest();
String returned;
try {
returned = sourceCode.getInternetData();
httpTest.setText(returned);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
这是应该获取HTML源代码的代码:
public class GetTest {
public String getInternetData() throws Exception {
BufferedReader in = null;
String data = null;
try {
HttpClient client = new DefaultHttpClient();
URI website = new URI(
"http://www.yahoo.com");
HttpGet request = new HttpGet();
request.setURI(website);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.separator");
while ((l = in.readLine()) != null) {
sb.append(l + nl);
}
in.close();
data = sb.toString();
return data;
} finally {
if (in != null) {
try {
in.close();
return data;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
我在清单中的权限:
<uses-permission android:name="android.permission.INTERNET" />
最后,这是我的logcat:
04-30 02:28:44.368: E/Trace(1095): error opening trace file: No such file or directory (2)
04-30 02:28:45.338: D/dalvikvm(1095): GC_FOR_ALLOC freed 51K, 7% free 2555K/2728K, paused 41ms, total 44ms
04-30 02:28:45.348: I/dalvikvm-heap(1095): Grow heap (frag case) to 3.216MB for 635812-byte allocation
04-30 02:28:45.398: D/dalvikvm(1095): GC_FOR_ALLOC freed 2K, 6% free 3174K/3352K, paused 45ms, total 45ms
04-30 02:28:45.447: D/dalvikvm(1095): GC_CONCURRENT freed <1K, 6% free 3177K/3352K, paused 5ms+4ms, total 57ms
04-30 02:28:45.509: W/System.err(1095): android.os.NetworkOnMainThreadException
04-30 02:28:45.509: W/System.err(1095): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
04-30 02:28:45.509: W/System.err(1095): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
04-30 02:28:45.509: W/System.err(1095): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
04-30 02:28:45.509: W/System.err(1095): at java.net.InetAddress.getAllByName(InetAddress.java:214)
04-30 02:28:45.518: W/System.err(1095): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
04-30 02:28:45.518: W/System.err(1095): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
04-30 02:28:45.518: W/System.err(1095): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
04-30 02:28:45.518: W/System.err(1095): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
04-30 02:28:45.518: W/System.err(1095): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
04-30 02:28:45.528: W/System.err(1095): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
04-30 02:28:45.528: W/System.err(1095): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
04-30 02:28:45.528: W/System.err(1095): at com.example.edittexttest.GetTest.getInternetData(GetTest.java:24)
04-30 02:28:45.528: W/System.err(1095): at com.example.edittexttest.MainActivity.onCreate(MainActivity.java:18)
04-30 02:28:45.528: W/System.err(1095): at android.app.Activity.performCreate(Activity.java:5104)
04-30 02:28:45.528: W/System.err(1095): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
04-30 02:28:45.528: W/System.err(1095): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
04-30 02:28:45.528: W/System.err(1095): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
04-30 02:28:45.528: W/System.err(1095): at android.app.ActivityThread.access$600(ActivityThread.java:141)
04-30 02:28:45.528: W/System.err(1095): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
04-30 02:28:45.538: W/System.err(1095): at android.os.Handler.dispatchMessage(Handler.java:99)
04-30 02:28:45.538: W/System.err(1095): at android.os.Looper.loop(Looper.java:137)
04-30 02:28:45.538: W/System.err(1095): at android.app.ActivityThread.main(ActivityThread.java:5041)
04-30 02:28:45.538: W/System.err(1095): at java.lang.reflect.Method.invokeNative(Native Method)
04-30 02:28:45.538: W/System.err(1095): at java.lang.reflect.Method.invoke(Method.java:511)
04-30 02:28:45.538: W/System.err(1095): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-30 02:28:45.538: W/System.err(1095): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-30 02:28:45.548: W/System.err(1095): at dalvik.system.NativeStart.main(Native Method)
04-30 02:28:45.758: D/gralloc_goldfish(1095): Emulator without GPU emulation detected.
感谢先进的帮助!
最佳答案 您的代码在主线程中执行网络操作.如果您的目标是Honeycomb或更高版本(3.0),则无法在主线程上执行网络操作.所以你得到了这个:
android.os.NetworkOnMainThreadException
有关详细信息,请参阅How to fix android.os.NetworkOnMainThreadException?.
如果你花一些时间学习如何使用AsyncTask,那将是很棒的.
无论如何,下面是一个如何使用它的粗略代码. (我试图修改代码中的东西.)
public class YoursActivity extends Activity {
private TextView httpTest;
/** Called when the activity is first created. */
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
httpTest = (TextView) findViewById(R.id.textView1);
new HttpTask().execute();
...
}
...
private class HttpTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
GetTest sourceCode = new GetTest();
String returned = "";
try {
returned = sourceCode.getInternetData();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return returned;
}
@Override
protected void onPostExecute(String returned) {
httpTest.setText(returned);
}
}
}