我整理了一个按原样工作的RSS阅读器,但是,我想使用HttpUrlConnection方法设置与RSS URL的连接。当我尝试它时,程序在我单击Read 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;
}
}
这是我使用的连接方法有效:
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;
}
}
感谢您提供的任何帮助!
答案 0 :(得分:4)
你需要做的是将它放入我称之为结果的字符串中。我已经为doInBackground附加了我的代码。通过将其添加到字符串,它可以存储Feed。它适用于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;
}