获取连接异常,连接超时:连接

时间:2015-10-26 05:27:21

标签: java

我正在运行一个简单的java程序来连接到硬编码的URL" http://www.google.co.in/?gws_rd=ssl"并且在尝试获取响应代码时:它会抛出连接超时异常。

代码段如下:

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

如果有人有决议权,请帮忙吗?

3 个答案:

答案 0 :(得分:1)

您是否使用urlConn = (HttpsURLConnection) url.openConnection();进行了检查。

答案 1 :(得分:0)

试试这个,

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();
}

答案 2 :(得分:0)

您支持代理的可能原因。确认您可以使用浏览器连接到URL。设置JVM的代理设置。这是设置代理设置的link