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:emily.command.fun.CatFactCommand.java

public static String getCatFact() {
    try {//from w  ww. j  av a  2s .  co m
        URL loginurl = new URL("https://catfact.ninja/fact");
        URLConnection yc = loginurl.openConnection();
        yc.setConnectTimeout(10 * 1000);
        BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
        String inputLine = in.readLine();
        JsonParser parser = new JsonParser();
        JsonObject array = parser.parse(inputLine).getAsJsonObject();
        return ":cat:  " + array.get("fact").getAsString();
    } catch (Exception e) {
        System.out.println(e);
    }
    return null;
}

From source file:skinsrestorer.shared.utils.MojangAPI.java

private static URLConnection setupConnection(URL url) throws IOException {
    URLConnection connection = url.openConnection();
    connection.setConnectTimeout(10000);
    connection.setReadTimeout(10000);//from  w ww. j  a  v a 2  s.c om
    connection.setUseCaches(false);
    connection.setDoInput(true);
    connection.setDoOutput(true);
    return connection;
}

From source file:Main.java

public static File getFileFromCacheOrURL(File cacheDir, URL url) throws IOException {
    Log.i(TAG, "getFileFromCacheOrURL(): url = " + url.toExternalForm());

    String filename = url.getFile();
    int lastSlashPos = filename.lastIndexOf('/');
    String fileNameNoPath = new String(lastSlashPos == -1 ? filename : filename.substring(lastSlashPos + 1));

    File file = new File(cacheDir, fileNameNoPath);

    if (file.exists()) {
        if (file.length() > 0) {
            Log.i(TAG, "File exists in cache as: " + file.getAbsolutePath());
            return file;
        } else {/*from w  ww  . j av a 2  s.c  o m*/
            Log.i(TAG, "Deleting zero length file " + file.getAbsolutePath());
            file.delete();
        }
    }

    Log.i(TAG, "File " + file.getAbsolutePath() + " does not exists.");

    URLConnection ucon = url.openConnection();
    ucon.setReadTimeout(5000);
    ucon.setConnectTimeout(30000);

    InputStream is = ucon.getInputStream();
    BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);
    FileOutputStream outStream = new FileOutputStream(file);
    byte[] buff = new byte[5 * 1024];

    // Read bytes (and store them) until there is nothing more to read(-1)
    int len;
    while ((len = inStream.read(buff)) != -1) {
        outStream.write(buff, 0, len);
    }

    // Clean up
    outStream.flush();
    outStream.close();
    inStream.close();
    return file;
}

From source file:com.netsteadfast.greenstep.util.WsServiceUtils.java

public static boolean testConnection(String wsdlAddress) throws Exception {
    if (StringUtils.isBlank(wsdlAddress)) {
        return true;
    }/*from   w ww  .  j a  v  a2s  .c  o m*/
    boolean status = false;
    try {
        URL url = new URL(wsdlAddress);
        URLConnection connection = url.openConnection();
        connection.setConnectTimeout(TIMEOUT);
        connection.setReadTimeout(TIMEOUT);
        if (connection.getContent() != null) {
            status = true;
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return status;
}

From source file:emily.util.YTUtil.java

/**
 * @param videocode youtubecode/*from  w w  w  .  j a v  a 2 s .c om*/
 * @return whats in the <title> tag on a youtube page
 */
public static String getTitleFromPage(String videocode) {
    String ret = "";
    try {
        URL loginurl = new URL("https://www.youtube.com/watch?v=" + videocode);
        URLConnection yc = loginurl.openConnection();
        yc.setConnectTimeout(10 * 1000);
        BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
        StringBuilder input = new StringBuilder();
        String inputLine;
        while ((inputLine = in.readLine()) != null)
            input.append(inputLine);
        in.close();
        int start = input.indexOf("<title>");
        int end = input.indexOf("</title>");
        ret = input.substring(start + 7, end - 10);
    } catch (Exception e) {
        System.out.println(e);
        e.printStackTrace();
    }
    return StringEscapeUtils.unescapeHtml4(ret);
}

From source file:nz.co.lolnet.lolnetachievements.Utility.Config.java

private static boolean retrieveAchievementConversionList() {
    boolean output = false;
    try {// w  w w.j a va  2 s.  c  om
        URL url = new URL("https://api-lnetachievements.rhcloud.com/api/achievementconversionlist");
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        conn.setConnectTimeout(API_TIMEOUT);

        // Get the response
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        ACHIEVEMENT_CONVERSION_LIST = (JSONArray) new JSONParser().parse(rd.readLine());
        rd.close();

        output = true;

    } catch (IOException | ParseException ex) {
        output = false;
    }
    return output;
}

From source file:nz.co.lolnet.lolnetachievements.Achievements.Achievements.java

private static JSONArray getPlayerAchievements(String playername)
        throws MalformedURLException, IOException, ParseException {
    URL url = new URL(
            "https://api-lnetachievements.rhcloud.com/api/achievements?playerName=" + playername.toLowerCase());
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);//from w  ww .ja v a 2s.c om
    conn.setConnectTimeout(API_TIMEOUT);

    // Get the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String temp = rd.readLine();
    rd.close();
    return (JSONArray) new JSONParser().parse(temp);
}

From source file:fuliao.fuliaozhijia.data.UserData.java

public static String download(String mediaId, String dir) {
    //      http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID
    URL source;//from   ww  w .  j  a v  a 2 s.  com
    try {
        source = new URL("http://file.api.weixin.qq.com/cgi-bin/media/get?access_token="
                + "oPaVk_NjH_TCX1fQhIVz_8DoRqE85Vx2E_sawJWQXpen5Q6HykjRnqA--6yE-y2VaQTU1f3vY5K-udylcgm55igkwa--7kVQ-KyDndcylmE"
                //WeixinAccessUtil.getAccessToken()
                + "&media_id=" + mediaId);
        URLConnection connection = source.openConnection();
        connection.setConnectTimeout(60 * 1000);
        connection.setReadTimeout(300 * 1000);
        InputStream input = connection.getInputStream();
        String fileType = connection.getHeaderField("Content-disposition");
        System.out.println("Content-disposition:" + fileType);
        String fileName = UUID.randomUUID().toString()
                + fileType.substring(fileType.lastIndexOf("."), fileType.length() - 1);
        File file = new File(dir + fileName);
        FileUtils.copyInputStreamToFile(input, file);
        return fileName;
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.sikuli.ide.extmanager.ExtensionManagerFrame.java

static String html2txt(String urlstring) throws IOException {
    URL url = new URL(urlstring);
    URLConnection yc = url.openConnection();
    yc.setConnectTimeout(5000);
    BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
    String txt = "";
    String inputLine;//from w  ww . j  a va2s.c om

    while ((inputLine = in.readLine()) != null) {
        txt = txt + inputLine;
    }
    in.close();

    return txt;

}

From source file:Main.java

/**
 * Return '' or error message if error occurs during URL connection.
 * /*from w w w  .j a  v  a2 s .co  m*/
 * @param url   The URL to ckeck
 * @return
 */
public static String getUrlStatus(String url) {
    URL u;
    URLConnection conn;
    int connectionTimeout = 500;
    try {
        u = new URL(url);
        conn = u.openConnection();
        conn.setConnectTimeout(connectionTimeout);

        // TODO : set proxy

        if (conn instanceof HttpURLConnection) {
            HttpURLConnection httpConnection = (HttpURLConnection) conn;
            httpConnection.setInstanceFollowRedirects(true);
            httpConnection.connect();
            httpConnection.disconnect();
            // FIXME : some URL return HTTP200 with an empty reply from server 
            // which trigger SocketException unexpected end of file from server
            int code = httpConnection.getResponseCode();

            if (code == HttpURLConnection.HTTP_OK) {
                return "";
            } else {
                return "Status: " + code;
            }
        } // TODO : Other type of URLConnection
    } catch (Exception e) {
        e.printStackTrace();
        return e.toString();
    }

    return "";
}