2016-01-23 52 views
0

我有这段代码,它很好地读取远程文件,但我不知道它是如何可能的,它会像读取第二个url url如果第一次失败。如何读取另一个远程URL Android如果第一个URL不可能

也就是说,我读了第一个文件的URL,如果可用,确定继续。 如果您无法读取第一个网址,则会访问第二个网址。

正如你可以添加第二个URL“备份” 谢谢。

// Code 

try { 
      // Create a URL for the desired page 
      URL url = new URL("http://myurl.com/archive.txt"); 

      // Read all the text returned by the server 
      BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); 

      network1 = in.readLine(); 
      network2 = in.readLine(); 
      network3 = in.readLine(); 
      network4 = in.readLine(); 

      in.close(); 
     } catch (MalformedURLException e) { 
     } catch (IOException e) { 
     } 



     // Code 



    } 

回答

1

使用这样的

String[] readUrl(String urlStr) throws Exception { 
    URL url = new URL(urlStr); 
    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); 
    String result = new String[4]; 
    for(i=0; i< 4; i++) { 
     result[i] = in.readLine(); 
    } 
    return result; 
} 

String[] tryMultipleUrls(String url1, String url2) { 
    String result[] = null; 
    try { 
     result = readUrl(url1); 
    } 
    catch(Exception ex) { 
     result = readUrl(url2); 
    } 
    return result; 
}