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:nz.co.lolnet.lolnetachievements.Achievements.Achievements.java

public static void awardPlayerAchievement(String playername, String achievementname)
        throws MalformedURLException, IOException, ParseException {

    JSONObject data = new JSONObject();
    data.put("serverName", Config.SERVER_NAME);
    data.put("serverKey", Config.SERVER_HASH);
    data.put("achievementName", LolnetAchievements.convertAchievementName(achievementname));
    data.put("playerName", playername.toLowerCase());

    if (Config.DEBUG_MODE) {
        System.out.println(data.toJSONString());
    }/*from w  ww .jav  a  2s  .c  o m*/

    URL url = new URL("https://api-lnetachievements.rhcloud.com/api/achievements");
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    conn.setConnectTimeout(API_TIMEOUT);
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data.toJSONString());
    wr.flush();
    wr.close();

    // Get the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String temp = rd.readLine();
    if (Config.DEBUG_MODE) {
        System.out.println(temp);
    }
    //JSONObject object = (JSONObject) new JSONParser().parse(temp);
    //System.out.println("");
    rd.close();
}

From source file:org.anyframe.oden.bundle.auth.AuthTest.java

private static URLConnection init(String url) throws MalformedURLException, IOException {
    URLConnection con = new URL(url).openConnection();
    con.setUseCaches(false);/* ww w . j  a  v  a 2s  .  c  o m*/
    con.setDoOutput(true);
    con.setDoInput(true);
    con.setConnectTimeout(TIMEOUT);
    con.setRequestProperty("Authorization", "Basic " + encode("oden", "oden0"));
    return con;
}

From source file:org.apache.hadoop.hdfs.web.URLConnectionFactory.java

/**
 * Sets timeout parameters on the given URLConnection.
 * /*w  w  w.j  a va2 s.  c  om*/
 * @param connection
 *          URLConnection to set
 * @param socketTimeout
 *          the connection and read timeout of the connection.
 */
private static void setTimeouts(URLConnection connection, int socketTimeout) {
    connection.setConnectTimeout(socketTimeout);
    connection.setReadTimeout(socketTimeout);
}

From source file:com.baidu.api.client.core.DownloadUtil.java

/**
 * Download the file pointed by the url and return the content as byte array.
 *
 * @param strUrl         The Url to be downloaded.
 * @param connectTimeout Connect timeout in milliseconds.
 * @param readTimeout    Read timeout in milliseconds.
 * @param maxFileSize    Max file size in BYTE.
 * @return The file content as byte array.
 *//*from   ww w .j  a v  a2  s.co  m*/
public static byte[] downloadFile(String strUrl, int connectTimeout, int readTimeout, int maxFileSize) {
    InputStream in = null;
    try {
        URL url = new URL(strUrl); // URL?
        URLConnection ucon = url.openConnection();
        ucon.setConnectTimeout(connectTimeout);
        ucon.setReadTimeout(readTimeout);
        ucon.connect();
        if (ucon.getContentLength() > maxFileSize) {
            String msg = "File " + strUrl + " size [" + ucon.getContentLength()
                    + "] too large, download stoped.";
            throw new ClientInternalException(msg);
        }
        if (ucon instanceof HttpURLConnection) {
            HttpURLConnection httpCon = (HttpURLConnection) ucon;
            if (httpCon.getResponseCode() > 399) {
                String msg = "Failed to download file " + strUrl + " server response "
                        + httpCon.getResponseMessage();
                throw new ClientInternalException(msg);
            }
        }
        in = ucon.getInputStream(); // ?
        byte[] byteBuf = new byte[BUFFER_SIZE];
        byte[] ret = null;
        int count, total = 0;
        // ??
        while ((count = in.read(byteBuf, total, BUFFER_SIZE - total)) > 0) {
            total += count;
            if (total + 124 >= BUFFER_SIZE)
                break;
        }
        if (total < BUFFER_SIZE - 124) {
            ret = ArrayUtils.subarray(byteBuf, 0, total);
        } else {
            ByteArrayOutputStream bos = new ByteArrayOutputStream(MATERIAL_SIZE);
            count = total;
            total = 0;
            do {
                bos.write(byteBuf, 0, count);
                total += count;
                if (total > maxFileSize) {
                    String msg = "File " + strUrl + " size exceed [" + maxFileSize + "] download stoped.";
                    throw new ClientInternalException(msg);
                }
            } while ((count = in.read(byteBuf)) > 0);
            ret = bos.toByteArray();
        }
        if (ret.length < MIN_SIZE) {
            String msg = "File " + strUrl + " size [" + maxFileSize + "] too small.";
            throw new ClientInternalException(msg);
        }
        return ret;
    } catch (IOException e) {
        String msg = "Failed to download file " + strUrl + " msg=" + e.getMessage();
        throw new ClientInternalException(msg);
    } finally {
        try {
            if (in != null)
                in.close();
        } catch (IOException e) {
            // ?
            System.out.println("Exception while close url - " + e.getMessage());
        }
    }
}

From source file:org.kootox.episodesmanager.services.WebHelper.java

/**
 * Get the document located at the URL url
 * @param url the url to download//from  www. ja v a  2s .c  o m
 * @return the downloaded Document
 */
public static Document readURL(String url) {

    if (log.isDebugEnabled()) {
        log.debug("Fetch document from : " + url);
    }

    //initiate the connection
    Document doc = null;
    InputStream in = null;
    try {
        URL distantURL = new URL(url);

        URLConnection conn = distantURL.openConnection();

        conn.setConnectTimeout(10000);

        in = conn.getInputStream();

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        doc = db.parse(in);

    } catch (UnknownHostException uhe) {
        log.error("Cannot connect to website, check your internet connection");
    } catch (MalformedURLException mue) {
        log.error("An error occured trying to contact website : " + mue.getMessage());
    } catch (IOException ioe) {
        log.error("An error occured trying to contact website : " + ioe.getMessage());
    } catch (ParserConfigurationException pce) {
        log.error("Error in configuration", pce);
    } catch (SAXException saxe) {
        log.error("Error in response", saxe);
    } finally {
        if (in != null) {
            try {
                in.close();

            } catch (IOException eee) {
                log.debug("Could not close stream", eee);
            }
        }
    }

    return doc;
}

From source file:org.apache.ambari.view.weather.CityResourceProvider.java

private static InputStream readFrom(String spec) throws IOException {
    URLConnection connection = new URL(spec).openConnection();

    connection.setConnectTimeout(5000);
    connection.setDoOutput(true);/*from   w  w  w  .jav a  2s  .c om*/
    return connection.getInputStream();
}

From source file:cz.ceskaexpedice.k5.k5jaas.basic.K5LoginModule.java

public static URLConnection openConnection(String urlString, String user, String pass)
        throws MalformedURLException, IOException {
    URL url = new URL(urlString);
    String userPassword = user + ":" + pass;
    String encoded = new String(Base64Coder.encode(userPassword.getBytes()));
    URLConnection uc = url.openConnection();
    uc.setReadTimeout(1000);//from   w  w w.j a  v a 2 s  . c  o m
    uc.setConnectTimeout(1000);
    uc.setRequestProperty("Authorization", "Basic " + encoded);
    return uc;
}

From source file:org.gitools.ui.app.welcome.WelcomeEditor.java

private static URL getWelcomeURL() {
    try {/*w  ww  .  j a  v  a2  s.com*/
        URL url = new URL(Settings.get().getWelcomeUrl() + "?appversion="
                + Application.getGitoolsVersion().toString() + "&uuid=" + Settings.get().getUuid());
        URLConnection connection = url.openConnection();
        connection.setConnectTimeout(10000);

        if (connection.getContentLength() != -1) {
            return url;
        }

    } catch (MalformedURLException e) {
    } catch (IOException e) {
    }

    return WelcomeEditor.class.getResource("/html/welcome.html");
}

From source file:com.iwgame.iwcloud.baidu.task.util.DownloadUtil.java

/**
 * url/* w ww.java  2  s  .  c  o  m*/
 * @param strUrl
 *            The Url to be downloaded.
 * @param connectTimeout
 *            Connect timeout in milliseconds.
 * @param readTimeout
 *            Read timeout in milliseconds.
 * @param maxFileSize
 *            Max file size in BYTE.
 * @return The file content as byte array.
 */
public static byte[] downloadFile(String strUrl, int connectTimeout, int readTimeout, int maxFileSize)
        throws IOException {
    InputStream in = null;
    try {
        URL url = new URL(strUrl); // URL?
        URLConnection ucon = url.openConnection();
        ucon.setConnectTimeout(connectTimeout);
        ucon.setReadTimeout(readTimeout);
        ucon.connect();
        if (ucon.getContentLength() > maxFileSize) {
            String msg = "File " + strUrl + " size [" + ucon.getContentLength()
                    + "] too large, download stoped.";
            logger.error(msg);
            throw new ClientInternalException(msg);
        }
        if (ucon instanceof HttpURLConnection) {
            HttpURLConnection httpCon = (HttpURLConnection) ucon;
            if (httpCon.getResponseCode() > 399) {
                String msg = "Failed to download file " + strUrl + " server response "
                        + httpCon.getResponseMessage();
                logger.error(msg);
                throw new ClientInternalException(msg);
            }
        }
        in = ucon.getInputStream(); // ?
        byte[] byteBuf = new byte[BUFFER_SIZE];
        byte[] ret = null;
        int count, total = 0;
        // ??
        while ((count = in.read(byteBuf, total, BUFFER_SIZE - total)) > 0) {
            total += count;
            if (total + 124 >= BUFFER_SIZE)
                break;
        }
        if (total < BUFFER_SIZE - 124) {
            ret = ArrayUtils.subarray(byteBuf, 0, total);
        } else {
            ByteArrayOutputStream bos = new ByteArrayOutputStream(MATERIAL_SIZE);
            count = total;
            total = 0;
            do {
                bos.write(byteBuf, 0, count);
                total += count;
                if (total > maxFileSize) {
                    String msg = "File " + strUrl + " size exceed [" + maxFileSize + "] download stoped.";
                    logger.error(msg);
                    throw new ClientInternalException(msg);
                }
            } while ((count = in.read(byteBuf)) > 0);
            ret = bos.toByteArray();
        }
        if (ret.length < MIN_SIZE) {
            String msg = "File " + strUrl + " size [" + maxFileSize + "] too small.";
            logger.error(msg);
            throw new ClientInternalException(msg);
        }
        return ret;
    } catch (IOException e) {
        String msg = "Failed to download file " + strUrl + " msg=" + e.getMessage();
        logger.error(msg);
        throw e;
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            logger.error("Exception while close url - ", e);
            throw e;
        }
    }
}

From source file:org.intermine.api.mines.FriendlyMineQueryRunner.java

/**
 * Run a query via the web service//from  ww w  .  ja v  a 2  s.  co  m
 *
 * @param urlString url to query
 * @return reader
 */
public static BufferedReader runWebServiceQuery(String urlString) {
    if (StringUtils.isEmpty(urlString)) {
        return null;
    }
    BufferedReader reader = null;
    try {
        if (!urlString.contains("?")) {
            // GET
            URL url = new URL(urlString);
            URLConnection conn = url.openConnection();
            conn.setConnectTimeout(CONNECT_TIMEOUT);
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            LOG.info("FriendlyMine URL (GET) " + urlString);
        } else {
            // POST
            String[] params = urlString.split("\\?");
            String newUrlString = params[0];
            String queryString = params[1];
            URL url = new URL(newUrlString);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(queryString);
            wr.flush();
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            LOG.info("FriendlyMine URL (POST) " + urlString);
        }
        return reader;
    } catch (Exception e) {
        LOG.info("Unable to access " + urlString + " exception: " + e.getMessage());
        return null;
    }
}