2014-01-13 183 views
2

我是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()開始工作時失敗。 我不知道如何解決它。

+0

您在代理設置參數後? – PopoFibo

+0

嗯,是的。我在代理人後面。 – Farsatanis

回答

0

如上所述,在建立連接之前,您需要設置代理參數/憑證

設置代理usernamepassword只有以防您的代理通過身份驗證。

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 { 
    ... 

我測試你的方法在一個代理和它完美的作品,即