Prakruti Pathik
Prakruti Pathik

Reputation: 392

Getting connection exception, connection timed out: connect

I am running a simple java program to connect to the hard coded URL "http://www.google.co.in/?gws_rd=ssl" and when trying to fetch a response code: it throws the connection timed out exception.

The code snippet as follows:

url = new URL("http://www.google.co.in/?gws_rd=ssl");
urlConn = (HttpURLConnection) url.openConnection();
**int responseCode = urlConn.getResponseCode(); ---> exception line**

Please help if any one have the resolution?

Upvotes: 0

Views: 767

Answers (3)

Yasothar
Yasothar

Reputation: 453

Did you check with urlConn = (HttpsURLConnection) url.openConnection();.

Upvotes: 1

pawinder gupta
pawinder gupta

Reputation: 1265

The proable reason that you are behind a proxy. Confirm that you are able to connect to the URL using the browser. Set the proxy settings for JVM. This is the link to set the proxy settings.

Upvotes: 0

Abdul Manaf
Abdul Manaf

Reputation: 5003

Try this one,

public static String callURL(String myURL) {
    System.out.println("Requeted URL:" + myURL);
    StringBuilder sb = new StringBuilder();
    URLConnection urlConn = null;
    InputStreamReader in = null;
    try {
        URL url = new URL(myURL);
        urlConn = url.openConnection();
        if (urlConn != null)
            urlConn.setReadTimeout(60 * 1000);
        if (urlConn != null && urlConn.getInputStream() != null) {
            in = new InputStreamReader(urlConn.getInputStream(),
                    Charset.defaultCharset());
            BufferedReader bufferedReader = new BufferedReader(in);
            if (bufferedReader != null) {
                int cp;
                while ((cp = bufferedReader.read()) != -1) {
                    sb.append((char) cp);
                }
                bufferedReader.close();
            }
        }
    in.close();
    } catch (Exception e) {
        throw new RuntimeException("Exception while calling URL:"+ myURL, e);
    } 

    return sb.toString();
}

Upvotes: 0

Related Questions