Example usage for java.net URLConnection setConnectTimeout

List of usage examples for java.net URLConnection setConnectTimeout

Introduction

In this page you can find the example usage for java.net URLConnection setConnectTimeout.

Prototype

public void setConnectTimeout(int timeout) 

Source Link

Document

Sets a specified timeout value, in milliseconds, to be used when opening a communications link to the resource referenced by this URLConnection.

Usage

From source file:com.jiubang.core.util.HttpUtils.java

/**
 * Open an URL connection. If HTTPS, accepts any certificate even if not
 * valid, and connects to any host name.
 * //from  w  w w  . j a va 2 s . c  o m
 * @param url
 *            The destination URL, HTTP or HTTPS.
 * @return The URLConnection.
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
private static URLConnection getConnection(URL url)
        throws IOException, NoSuchAlgorithmException, KeyManagementException {
    URLConnection conn = url.openConnection();
    if (conn instanceof HttpsURLConnection) {
        // Trust all certificates
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(new KeyManager[0], TRUST_MANAGER, new SecureRandom());
        SSLSocketFactory socketFactory = context.getSocketFactory();
        ((HttpsURLConnection) conn).setSSLSocketFactory(socketFactory);

        // Allow all hostnames
        ((HttpsURLConnection) conn).setHostnameVerifier(HOSTNAME_VERIFIER);

    }
    conn.setConnectTimeout(SOCKET_TIMEOUT);
    conn.setReadTimeout(SOCKET_TIMEOUT);
    return conn;
}

From source file:mas.MAS_TOP_PAPERS.java

/**
 * @param args the command line arguments
 *///from  www.  j  av a 2s .c  om
public static String getData_old(String url_org, int start) {
    try {
        String complete_url = url_org + "&$skip=" + start;
        //            String url_str = generateURL(url_org, prop);
        URL url = new URL(complete_url);
        URLConnection yc = url.openConnection();
        yc.setConnectTimeout(25 * 1000);
        yc.setReadTimeout(25 * 1000);
        BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
        String inputLine;
        StringBuffer result = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            //                System.out.println(inputLine);
            result.append(inputLine);
        }
        in.close();
        return result.toString();
    } catch (MalformedURLException ex) {
        Logger.getLogger(MAS_TOP_PAPERS.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(MAS_TOP_PAPERS.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:mas.MAS_VLDB.java

/**
 * @param args the command line arguments
 *///from   w ww . j ava2  s . c  o  m
public static String getData_old(String url_org, int start) {
    try {
        String complete_url = url_org + "&$skip=" + start;
        //            String url_str = generateURL(url_org, prop);
        URL url = new URL(complete_url);
        URLConnection yc = url.openConnection();
        yc.setConnectTimeout(25 * 1000);
        yc.setReadTimeout(25 * 1000);
        BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
        String inputLine;
        StringBuffer result = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            //                System.out.println(inputLine);
            result.append(inputLine);
        }
        in.close();
        return result.toString();
    } catch (MalformedURLException ex) {
        Logger.getLogger(MAS_VLDB.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(MAS_VLDB.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:com.wareninja.opensource.common.wsrequest.HttpUtils.java

/**
 * Open an URL connection. If HTTPS, accepts any certificate even if not
 * valid, and connects to any host name.
 * /* ww w .  j  a  v a2 s.c o  m*/
 * @param url
 *            The destination URL, HTTP or HTTPS.
 * @return The URLConnection.
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
public static URLConnection getConnection(URL url)
        throws IOException, NoSuchAlgorithmException, KeyManagementException {
    URLConnection conn = url.openConnection();
    if (conn instanceof HttpsURLConnection) {
        // Trust all certificates
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(new KeyManager[0], TRUST_MANAGER, new SecureRandom());
        SSLSocketFactory socketFactory = context.getSocketFactory();
        ((HttpsURLConnection) conn).setSSLSocketFactory(socketFactory);

        // Allow all hostnames
        ((HttpsURLConnection) conn).setHostnameVerifier(HOSTNAME_VERIFIER);

    }
    conn.setConnectTimeout(SOCKET_TIMEOUT);
    conn.setReadTimeout(SOCKET_TIMEOUT);
    return conn;
}

From source file:org.spoutcraft.launcher.rest.RestAPI.java

public static HashMap<String, Minecraft> getMinecraftVersions() throws RestfulAPIException {
    InputStream stream = null;/*from  w  w w  .jav a2  s  .  c  om*/
    try {
        URLConnection conn = new URL(getMinecraftVersionURL()).openConnection();
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
        conn.setConnectTimeout(15000);
        conn.setReadTimeout(15000);

        stream = conn.getInputStream();
        HashMap<String, Minecraft> versions = mapper.readValue(stream,
                new TypeReference<Map<String, Minecraft>>() {
                });

        for (Minecraft result : versions.values()) {
            if (result.hasError()) {
                throw new RestfulAPIException("Error in json response: " + result.getError());
            }
        }

        return versions;
    } catch (SocketTimeoutException e) {
        throw new RestfulAPIException("Timed out accessing URL [" + getMinecraftVersionURL() + "]", e);
    } catch (IOException e) {
        throw new RestfulAPIException("Error accessing URL [" + getMinecraftVersionURL() + "]", e);
    } finally {
        IOUtils.closeQuietly(stream);
    }
}

From source file:org.spoutcraft.launcher.rest.RestAPI.java

public static List<Article> getNews() throws RestfulAPIException {
    InputStream stream = null;//from  www  .  jav a2  s.co m
    try {
        URLConnection conn = new URL(getPlatformAPI() + "news/").openConnection();
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
        conn.setConnectTimeout(15000);
        conn.setReadTimeout(15000);

        stream = conn.getInputStream();
        List<Article> versions = mapper.readValue(stream, new TypeReference<List<Article>>() {
        });

        for (Article result : versions) {
            if (result.hasError()) {
                throw new RestfulAPIException("Error in json response: " + result.getError());
            }
        }

        return versions;
    } catch (SocketTimeoutException e) {
        throw new RestfulAPIException("Timed out accessing URL [" + getMinecraftVersionURL() + "]", e);
    } catch (IOException e) {
        throw new RestfulAPIException("Error accessing URL [" + getMinecraftVersionURL() + "]", e);
    } finally {
        IOUtils.closeQuietly(stream);
    }
}

From source file:org.asimba.util.saml2.metadata.provider.MetadataProviderUtil.java

/**
 * Create a new HTTP Metadata Provider from the provided URL and HTTP settings<br/>
 * An exception is thrown when the provider could not be initiated.
 * //w  w  w . jav a  2 s .  co m
 * @param sMetadataURL
 * @param sMetadataTimeout
 * @param oParserPool
 * @param oMPM
 * @return
 * @throws OAException
 */
public static MetadataProvider newHTTPMetadataProvider(String sId, String sMetadataURL, int iTimeout,
        ParserPool oParserPool, IMetadataProviderManager oMPM) throws OAException {
    MetadataProvider oProvider = null;

    // Check URL format
    URL oURLTarget = null;
    try {
        oURLTarget = new URL(sMetadataURL);
    } catch (MalformedURLException e) {
        _oLogger.error("Invalid url for metadata: " + sMetadataURL, e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }

    // Check valid and existing destination (with configured timeout settings)
    try {
        URLConnection oURLConnection = oURLTarget.openConnection();
        if (iTimeout <= 0) {
            oURLConnection.setConnectTimeout(3000);
            oURLConnection.setReadTimeout(3000);
        } else {
            oURLConnection.setConnectTimeout(iTimeout);
            oURLConnection.setReadTimeout(iTimeout);
        }

        oURLConnection.connect();
    } catch (IOException e) {
        _oLogger.warn("Could not connect to metadata url: " + sMetadataURL + "(using timout "
                + (iTimeout == 0 ? "3000" : iTimeout) + "ms)", e);
    }

    // Establish dedicated refresh timer:
    String sTimername = "Metadata_HTTP-" + (oMPM == null ? "" : oMPM.getId() + "-") + sId + "-Timer";
    Timer oRefreshTimer = new Timer(sTimername, true);

    // Establish HttpClient
    HttpClient oHttpClient = new HttpClient();

    if (iTimeout > 0) {
        // Set configured Timeout settings
        oHttpClient.getParams().setSoTimeout(iTimeout);
    }

    oProvider = MetadataProviderUtil.createProviderForURL(sMetadataURL, oParserPool, oRefreshTimer,
            oHttpClient);

    if (oProvider != null) {
        // Start managing it:
        if (oMPM != null) {
            oMPM.setProviderFor(sId, oProvider, oRefreshTimer);
        }
    } else {
        // Unsuccessful creation; clean up created Timer
        oRefreshTimer.cancel();
    }

    return oProvider;
}

From source file:com.minoritycode.Application.java

public static URLConnection makeConnection(String url, boolean useProxy) {

    URLConnection connection = null;
    try {/* w w w.  ja v a2s.co  m*/
        if (useProxy) {
            connection = new URL(url).openConnection(Application.proxy);
        } else {
            connection = new URL(url).openConnection();
        }
        connection.setRequestProperty("Accept-Charset", charset);
        connection.setConnectTimeout(30000);
    } catch (IOException e) {
        e.printStackTrace();
        Application.errorBoards.put(url, e.getMessage());
        logger.logLine(e.getMessage());
        return null;
    }

    return connection;
}

From source file:com.ibuildapp.romanblack.FanWallPlugin.data.Statics.java

/**
 * download file url and save it//w  w w .ja  v a2 s .  c o m
 *
 * @param url
 */
public static String downloadFile(String url) {
    int BYTE_ARRAY_SIZE = 1024;
    int CONNECTION_TIMEOUT = 30000;
    int READ_TIMEOUT = 30000;

    // downloading cover image and saving it into file
    try {
        URL imageUrl = new URL(URLDecoder.decode(url));
        URLConnection conn = imageUrl.openConnection();
        conn.setConnectTimeout(CONNECTION_TIMEOUT);
        conn.setReadTimeout(READ_TIMEOUT);
        BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());

        File resFile = new File(cachePath + File.separator + Utils.md5(url));
        if (!resFile.exists()) {
            resFile.createNewFile();
        }

        FileOutputStream fos = new FileOutputStream(resFile);
        int current = 0;
        byte[] buf = new byte[BYTE_ARRAY_SIZE];
        Arrays.fill(buf, (byte) 0);
        while ((current = bis.read(buf, 0, BYTE_ARRAY_SIZE)) != -1) {
            fos.write(buf, 0, current);
            Arrays.fill(buf, (byte) 0);
        }

        bis.close();
        fos.flush();
        fos.close();
        Log.d("", "");
        return resFile.getAbsolutePath();
    } catch (SocketTimeoutException e) {
        return null;
    } catch (IllegalArgumentException e) {
        return null;
    } catch (Exception e) {
        return null;
    }
}

From source file:org.wso2.carbon.cloud.gateway.agent.CGAgentUtils.java

private static URLConnection getURLConnection(URL url) throws CGException {
    URLConnection connection;
    if (url.getProtocol().equalsIgnoreCase("https")) {
        String msg = "Connecting through doesn't support";
        log.error(msg);/* w  w w  .  j  a v a  2 s.  c o  m*/
        throw new CGException(msg);
    } else {
        try {
            connection = url.openConnection();
        } catch (IOException e) {
            throw new CGException("Could not open the URL connection", e);
        }
    }
    connection.setReadTimeout(getReadTimeout());
    connection.setConnectTimeout(getConnectTimeout());
    connection.setRequestProperty("Connection", "close"); // if http is being used
    return connection;
}