RSS阅读器openStream()
问题描述:
我是Java新手,但真的想变得更好。我正在尝试写一个简单的RSS阅读器。这里是代码:RSS阅读器openStream()
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()
开始工作时失败。 我不知道如何解决它。
答
如上所述,在建立连接之前,您需要设置代理参数/凭证。
设置代理username
和password
只有以防您的代理通过身份验证。
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 {
...
我测试你的方法在一个代理和它完美的作品,即
您在代理设置参数后? – PopoFibo
嗯,是的。我在代理人后面。 – Farsatanis