We can have the primary and secondary urls in a configuration file and load them to a list at the beginning of the system. For the demonstration purpose I have hard coded list of urls.
We can achieve it easily by checking the response code sent by the server. I believe the code it self-explanatory.
public class Envision { public static void main(String[] args) throws MalformedURLException { HttpURLConnection httpURLConnection = null; InputStream inputStream = null; BufferedReader bufferedReader = null; String result = ""; String inStr = null; List<URL> urls = new ArrayList<URL>(); urls.add(new URL("http://example_primary.com")); urls.add(new URL("http://example_secondary.com")); try { for (int i = 0; i < urls.size(); i++) { try { httpURLConnection = (HttpURLConnection) urls.get(i).openConnection(); inputStream = httpURLConnection.getInputStream(); bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); int responseCode = httpURLConnection.getResponseCode(); if (responseCode == 200) { while ((inStr = bufferedReader.readLine()) != null) { result = result + inStr; } break; } } catch (Exception e) { System.out.println("Error: While requesting data from server "+urls.get(i)+" " + e.getMessage() ); } } System.out.println(">>>>Res: " + result); } catch (Exception e) { System.out.println("Error: While requesting data from server" + e.getMessage()); } } }
Happy Coding!