Android - 尝试使用网络时出现未知错误
我刚刚开始开发 Android 应用程序。 我在网络方面遇到了一些问题。 如果我运行以下代码,我会收到“未知错误”异常消息:
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.client.ClientProtocolException;
import.org.apache.http.client.methods.HttpGet;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Menu extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DefaultHttpClient client = new DefaultHttpClient();
HttpGet method = new HttpGet("http://www.google.com");
try {
client.execute(method);
TextView t = (TextView) findViewById(R.id.myTextView);
t.setText("Ok");
} catch (ClientProtocolException e) {
TextView t = (TextView) findViewById(R.id.myTextView);
t.setText(e.getMessage());
} catch (IOException e) {
TextView t = (TextView) findViewById(R.id.myTextView);
t.setText(e.getMessage());
}
}
}
我一直在查找该错误,它似乎相当常见。 这是模拟器上DNS解析的问题。 但是,我可以毫无问题地使用模拟器上的浏览器并访问我想要的任何网站。 我也尝试过用 IP 地址替换域名,但没有成功。
我该如何解决这个问题? 我正在使用 Windows Vista 并使用 ADT 插件在 eclipse 中进行开发。
I've just started developing Android applications. I'm having a little problem with networking. If I run the following code I get an "unknown error" exception message:
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.client.ClientProtocolException;
import.org.apache.http.client.methods.HttpGet;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Menu extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DefaultHttpClient client = new DefaultHttpClient();
HttpGet method = new HttpGet("http://www.google.com");
try {
client.execute(method);
TextView t = (TextView) findViewById(R.id.myTextView);
t.setText("Ok");
} catch (ClientProtocolException e) {
TextView t = (TextView) findViewById(R.id.myTextView);
t.setText(e.getMessage());
} catch (IOException e) {
TextView t = (TextView) findViewById(R.id.myTextView);
t.setText(e.getMessage());
}
}
}
I've been lookign up the error and it seems fairly common. It's a problem with DNS resolution on the emulator. However, I can use the browser on the emulator without a problem and visit any website I want. I've also tried replacing the domains with IP addresses without luck.
How can I fix this problem? I'm using Windows Vista and developing in eclipse with the ADT plugin.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据此 博客,您需要在 AndroidManifest 中为您的应用程序设置“INTERNET”权限.xml
According to this blog, you need to set the 'INTERNET' permission to your application in your AndroidManifest.xml