1

I am trying to connect to the internet with the user defined proxy settings. I have set the setReadTimeout to 5 seconds. If the configured proxy is not correct, then we wont be able to connect to internet and i am using the following code, but the read time out is not at all happening.

            URL u = new URL("http://www.google.com/");
            System.out.println("Checking internet connection availability.....");
            System.setProperty("java.net.useSystemProxies", "true");
            System.setProperty("http.proxyHost", proxyHost);
            System.setProperty("http.proxyPort", proxyPort);
            HttpURLConnection uc = (HttpURLConnection) u.openConnection();
            uc.setReadTimeout(5000);
            System.out.println("Response code : " + uc.getResponseCode());
            System.out.println("Internet connection is available.....");

If i run the above code, then program is keep on executing and not getting terminated in 5 seconds.

Can anybody help me out here about the problem in my code ?

Thanks in advance.

1 Answer 1

2

Try also adding uc.setConnectTimeout(5000);

Edit: Final solution

Use uc.connect(); before getting the response code.

Also, add the proxy configuration while opening the HttpURLConnection.

Like this :

HttpURLConnection uc = (HttpURLConnection) u.openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(myProxyHost, Integer.parseInt(myProxyPort))));
Sign up to request clarification or add additional context in comments.

4 Comments

Weird, I have a code similar to yours excepted that I'm using the proxy-vole library to handle proxy's configuration and it seems to work perfectly.
Maybe you can try using the uc.connect(); before getting the response code?
Thanks Padrus. I have used uc.connect() It is working now. Also, I have also added the proxy config while opening the HttpURLConnection like as follows, HttpURLConnection uc = (HttpURLConnection) u.openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(myProxyHost, Integer.parseInt(myProxyPort))));
Nice, I'll edit my answer so maybe you can accept it and it could help other users.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.