gpt4 book ai didi

java - 安卓网络连接失败

转载 作者:行者123 更新时间:2023-12-01 14:04:55 25 4
gpt4 key购买 nike

我很难将应用程序连接到互联网并检索 html 源。一直在寻找解决方案,但没有找到。希望有人能帮忙。这是我的代码:

public class Main extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

final EditText et = (EditText) findViewById(R.id.editText1);
final Button b = (Button) findViewById(R.id.button1);
final TextView tv = (TextView) findViewById(R.id.textView1);

b.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {

try {
URL url=null;
url = new URL(et.getText().toString());
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
tv.append(line);
}

} catch (Exception e) {

}

}
});
}

我还添加了 INTERNET 权限..

最佳答案

您需要将连接到互联网并获取数据的代码移动到 AsyncTask 。这是由于 NetworkOnMainThreadException 造成的。当应用程序尝试在其主线程上执行网络操作时,会引发此异常。

尽管可以通过使用 StrictMode.ThreadPolicy 来解决此问题,但强烈建议不要这样做。

这是 docs 的摘录.

NetworkOnMainThreadException:-

This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged.

参见this question了解更多信息。

关于java - 安卓网络连接失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18980727/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com