gpt4 book ai didi

java - 无法在android中使用httpconnection进行连接

转载 作者:太空宇宙 更新时间:2023-11-03 10:52:26 26 4
gpt4 key购买 nike

我使用的是 android 2.3.3,我制作了一个运行良好的 rss 阅读器,然后我将那个简单的 rss 阅读器的代码集成到另一个 Activity 中,只需仔细复制粘贴,那里没有错误。

问题是当我在我的模拟器上运行应用程序时它给我错误连接异常。然后我通过在 try block 中的每一行之后放置 toasts 发现问题出在 httpconnection.connect(); 行。

我在 android list 中添加了权限,而我的 logcat 给出了 javaio exception:error connecting 的警告。

    try {
HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
//Toast.makeText(this, "urlconnection passed", Toast.LENGTH_SHORT).show();
httpURLConnection.setAllowUserInteraction(false);
httpURLConnection.setInstanceFollowRedirects(true);
//Toast.makeText(this, "setting response method", Toast.LENGTH_SHORT).show();
httpURLConnection.setRequestMethod("GET");
//Toast.makeText(this, "connecting", Toast.LENGTH_SHORT).show();
httpURLConnection.connect();
Toast.makeText(this, "on response code", Toast.LENGTH_SHORT).show();
response = httpURLConnection.getResponseCode();
//Toast.makeText(this, "response code passed", Toast.LENGTH_SHORT).show();
if (response == HttpURLConnection.HTTP_OK) {
//Toast.makeText(this, "OK", Toast.LENGTH_SHORT).show();
inputStream = httpURLConnection.getInputStream();
}

} catch (Exception e) {
// TODO: handle exception
throw new IOException("Error connecting");
}

这里是创建对象的代码:

URL url = new URL(UrlString);
URLConnection connection = url.openConnection();
if (!(connection instanceof HttpURLConnection))
throw new IOException("Not a HTTP connection");

最佳答案

It gives networkonmainthread exception

这意味着您正在主线程上进行网络操作,而这在严格模式下是不允许的。

“在主线程中”通常意味着您在事件处理程序中执行此操作,例如 onResumeonPause 或在 onClick 你的 OnClickListener 的方法。您可以查看这篇文章 ( Painless threading ) 以了解问题所在以及为什么不允许这样做。通常,如果您在主线程中执行网络操作,它会阻塞 GUI 事件的处理,如果网络操作缓慢,您的应用程序将无法响应。

Strict Mode出现在 API 级别 9 中,因此这解释了为什么如果最低 SDK 版本为 10 会出现问题,以及为什么它适用于最低 SDK 版本 8。

你应该使用 AsyncTask或其他在后台执行此操作的方法。可以引用1为此。

关于java - 无法在android中使用httpconnection进行连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11282610/

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