为什么我用来从网站读取文件的代码可以在 java 中运行,但不能在 android 模拟器中运行?
当我使用 eclipse 在常规 .java 中测试代码时,下面的代码可以为我提供文本“brendan's android”,但当我在 android 模拟器的主活动中运行它时,会引发错误异常。
我尝试使用 HttpURLConnection 而不是 URLConnection,但这并没有解决问题。
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
String urlStr = "http://www.brendan-weinstein.com/android.html";
URL url = new URL(urlStr);
URLConnection conn = (URLConnection) url.openConnection();
InputStreamReader inStream = new InputStreamReader(conn.getInputStream());
BufferedReader rd = new BufferedReader(inStream);
String testline = rd.readLine();
Toast.makeText(GenForm.this, testline, Toast.LENGTH_SHORT).show();
rd.close();
}
catch(IOException ex) {
Toast.makeText(GenForm.this, "reader did not work", Toast.LENGTH_LONG).show();
}
}
The below code works for giving me the text "brendan's android" when I test the code in a regular .java with eclipse but throws me an error exception when I run it in the main activity for the android emulator.
I have tried using HttpURLConnection instead of URLConnection and that did not fix the problem.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
String urlStr = "http://www.brendan-weinstein.com/android.html";
URL url = new URL(urlStr);
URLConnection conn = (URLConnection) url.openConnection();
InputStreamReader inStream = new InputStreamReader(conn.getInputStream());
BufferedReader rd = new BufferedReader(inStream);
String testline = rd.readLine();
Toast.makeText(GenForm.this, testline, Toast.LENGTH_SHORT).show();
rd.close();
}
catch(IOException ex) {
Toast.makeText(GenForm.this, "reader did not work", Toast.LENGTH_LONG).show();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你能粘贴异常吗?是什么样的异常呢?
随机猜测:您是否在清单中添加了对互联网权限的需求?
编辑:
Could you paste the exception? What kind of exception is it?
Random guess: did you add the need for internet permissions to your manifest?
edit: