我是 Java 的新手,但真的想在这方面做得更好。我正在尝试编写一个简单的 RSS 阅读器。这是代码:
import java.io.*;
import java.net.*;
public class RSSReader {
public static void main(String[] args) {
System.out.println(readRSS("http://www.usnews.com/rss/health-news"));
}
public static String readRSS(String urlAddress){
try {
URL rssUrl = new URL(urlAddress);
BufferedReader in = new BufferedReader(new InputStreamReader(rssUrl.openStream()));
String sourceCode = "";
String line;
while((line = in.readLine())!=null){
if(line.contains("<title>")){
int firstPos = line.indexOf("<title>");
String temp = line.substring(firstPos);
temp = temp.replace("<title>","");
int lastPos = temp.indexOf("</title>");
temp = temp.substring(0,lastPos);
sourceCode +=temp+"\n";
}
}
System.out.println("YAAAH"+sourceCode);
in.close();
return sourceCode;
} catch (MalformedURLException ue) {
System.out.println("Malformed URL");
} catch (IOException ioe) {
System.out.println("WTF?");
}
return null;
}
}
但它一直在捕获 IOException,我看到了“WTF”。
我意识到当 OpenStream()
开始工作时整个程序失败了。
我不知道如何修复它。
最佳答案
如前所述,您需要在建立连接之前设置您的代理参数/凭据。
设置代理用户名
和密码
仅以防您的代理通过身份验证。
public static String readRSS(String urlAddress) {
System.setProperty("http.proxyHost", YOUR_PROXY_HOST);
System.setProperty("http.proxyPort", YOUR_PROXY_PORT);
//Below 2 for authenticated proxies only
System.setProperty("http.proxyUser", YOUR_USERNAME);
System.setProperty("http.proxyPassword", YOUR_PASSWORD);
try {
...
我在代理后面测试了你的方法,它在设置参数后完美运行
关于java - RSS 阅读器 openStream(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21093362/