Ricky.C
Ricky.C

Reputation: 105

How to refresh website until server has response ? in Java?

I try to entry a busy website but always get the busy server result(error 500).

And I would like to use java code to loop the website until I can entry the website but i only know how to get the response code don't know how to open it in browse.

How to open the website in the connection of HttpURLConnection in browse or is there any other way to open or loop the website until no error? Many thanks!!!

import java.net.URL;
import java.io.IOException;
import java.net.HttpURLConnection;

public class test{
     public static String URL = "http://www.example.com/";
     public static void main (String args[]) throws Exception{

       int i =0;
       while(i==0){
       URL url = new URL("http://www.example.com/");
       HttpURLConnection connection = (HttpURLConnection)url.openConnection();
       connection.setRequestMethod("GET");
       connection.connect();
       int code = connection.getResponseCode();
        if (code != 500){
              //how to open the no error website.
           }
       System.out.println(code);
     }
    }

   }

Upvotes: 0

Views: 418

Answers (1)

royalghost
royalghost

Reputation: 2808

If you would like to open a website upon receiving the 200 HTTP Status, you can do something like below inside your if ... else statement :

   if (code == 200){
      //how to open the no error website.
      if (Desktop.isDesktopSupported()) {
           Desktop.getDesktop().browse(url.toURI()); //referring to the url connection already created
           System.exit(0);
       }
   }

Upvotes: 1

Related Questions