SetConnectTimeout has no effect, and setconnecttimeout does not.
One problem I encountered in the project is to determine the public network and private network. So I wrote a method using the following code:
// Determine whether the public static boolean openUrl () {HttpURLConnection conn = null; String myString = ""; InputStream is = null; BufferedInputStream bis = null; try {URL url = new URL ("http://www.baidu.com/index.html"); conn = (HttpURLConnection) url. openConnection (); conn. setConnectTimeout (1500); conn. setRequestMethod ("GET"); // sets the Request Method conn. connect (); // establish the actual connection to the remote object if (conn. getResponseCode ()! = HttpURLConnection. HTTP_ OK) {System. out. println ("network error exception !!!! "); Return false;} is = conn. getInputStream (); bis = new BufferedInputStream (is); // use ByteArrayBuffer to cache ByteArrayBuffer baf = new ByteArrayBuffer (50); int current = 0; while (current = bis. read ())! =-1) {baf. append (byte) current);} myString = EncodingUtils. getString (baf. toByteArray (), "UTF-8");} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace (); return false;} finally {try {bis. close (); is. close ();} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace ();} if (conn! = Null) {conn. disconnect (); // disconnect} if (myString. indexOf ("baidu.com")>-1) {return true;} else {return false ;}}In the code, we can see that I set the connection timeout to 1500 milliseconds.
conn.setConnectTimeout(1500);
However, the actual situation is that when the private network (cannot access Baidu) was at that time, it was not an exception that timed out in 1.5 seconds. This problem plagued two days,
You can also query a lot of data on the Internet. Some people say that you have to set the read timeout conn. setReadTimeout (1500,
When someone is using it, check the console and find that the system will automatically try it many times after 1500 milliseconds of access (the total number of times is not counted)
The access timeout exception is thrown for a long time. As a result, we can see that I set the 1500 millisecond timeout result to a few minutes before giving me the timeout exception. I feel that the set timeout time has no effect.
Let's talk about my solution. I personally passed the test. If there is a good solution, please point out:
Because the system will automatically throw an exception after many times of timeout, so I set the exception timeout time to a little shorter, for example, I set it to 500 milliseconds, the public network can be accessed normally, and the private network can quickly throw exceptions to achieve my goal.
In addition, another way to judge the public network and private network is to use ping. Remember to start a service area to process the ping and then stop the modification process. Otherwise, the second ping may be blocked.