[英]Using HttpUrlconnection in Rss Reader causes Android to hang
I put together an RSS reader that works as-is but, I want to setup the connection to the RSS URL using HttpUrlConnection method. 我整理了一个RSS阅读器,它按原样工作,但我想使用HttpUrlConnection方法设置与RSS URL的连接。 When I tried it, the program locked up after I clicked Read Rss button:
当我尝试它时,在单击“读取Rss”按钮后,该程序被锁定:
private class getRssFeedTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
try {
URL rssUrl = new URL(params[0]);
HttpURLConnection urlIn = (HttpURLConnection) rssUrl.openConnection();
InputStream in = new BufferedInputStream(urlIn.getInputStream());
String line;
feed = "";
while ((line = in.toString()) != null) {
feed += line;
}
in.close();
return feed;
} catch (MalformedURLException ue) {
System.out.println("Malformed URL");
} catch (IOException ioe) {
System.out.println("The URL is unreachable");
}
return null;
}
}
This is the connection method I am stuck using which works: 这是我坚持使用的连接方法,可以起作用:
private class getRssFeedTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
try {
URL rssUrl = new URL(params[0]);
BufferedReader in = new BufferedReader(new InputStreamReader(rssUrl.openStream()));
String line;
feed = "";
while ((line = in.readLine()) != null) {
feed += line;
}
in.close();
return feed;
} catch (MalformedURLException ue) {
System.out.println("Malformed URL");
} catch (IOException ioe) {
System.out.println("The URL is unreachable");
}
return null;
}
}
Thanks for any help you can provide! 感谢您的任何帮助,您可以提供!
What you need to do is put it into a string I called it results. 您需要做的是将其放入一个我称之为结果的字符串中。 I have attached my code for the doInBackground.
我已经为doInBackground附加了代码。 By adding it to a string it has a place to store the feed.
通过将其添加到字符串中,它可以存储提要。 And it works for the rss reader.
它适用于RSS读者。
public String doInBackground(String... urls){
String result = "";
try{
URL url = new URL(urls[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream in = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while((line = reader.readLine()) != null){
result = result + line;
}
conn.disconnect();
}
catch(Exception e){
Log.e("ERROR Fetching ", e.toString());
}
return result;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.