Example usage for java.net HttpURLConnection setConnectTimeout

List of usage examples for java.net HttpURLConnection setConnectTimeout

Introduction

In this page you can find the example usage for java.net HttpURLConnection 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.surfs.storage.common.util.HttpUtils.java

public static String invokeHttpForGet(String path, String... agrs) throws IOException {
    URL url = new URL(path);
    LogFactory.info("rest url:" + url.toString());
    HttpURLConnection con = null;
    try {/*from   w  w w.  ja  v  a 2 s.  c o m*/
        con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.setConnectTimeout(10000);
        con.setReadTimeout(1000 * 60 * 30);
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setUseCaches(false);

        for (String string : agrs) {
            con.setRequestProperty("Content-type", "application/json");
            con.setRequestMethod("POST");
            OutputStream out = con.getOutputStream();
            out.write(string.getBytes("UTF-8"));
        }

        if (con.getResponseCode() != 200)
            throw new ConnectException(con.getResponseMessage());

        InputStream is = con.getInputStream();

        return readResponse(is);

    } catch (IOException e) {
        throw e;
    } finally {
        if (con != null) {
            con.disconnect();
        }
    }
}

From source file:jfix.util.Urls.java

/**
 * Returns true if given url can be connected via HTTP within given timeout
 * (specified in seconds). Otherwise the url might be broken.
 *//*from ww w .j  av a 2 s .c  om*/
public static boolean isConnectable(String url, int timeout) {
    try {
        URLConnection connection = new URL(url).openConnection();
        if (connection instanceof HttpURLConnection) {
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            httpConnection.setConnectTimeout(timeout * 1000);
            httpConnection.setReadTimeout(timeout * 1000);
            httpConnection.connect();
            int response = httpConnection.getResponseCode();
            httpConnection.disconnect();
            return response == HttpURLConnection.HTTP_OK;
        }
    } catch (Exception e) {
        return false;
    }
    return false;
}

From source file:jfix.util.Urls.java

/**
 * Returns the status code for connecting given url with given timeout.
 * Returns 0 if an IOException occurs./*from   w  ww.j  av  a 2 s.  co m*/
 */
public static int getStatus(String url, int timeout) {
    try {
        URLConnection connection = new URL(url).openConnection();
        if (connection instanceof HttpURLConnection) {
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            httpConnection.setConnectTimeout(timeout * 1000);
            httpConnection.setReadTimeout(timeout * 1000);
            httpConnection.connect();
            int response = httpConnection.getResponseCode();
            httpConnection.disconnect();
            return response;
        }
    } catch (IOException e) {
        // pass
    }
    return 0;
}

From source file:org.cytoscape.app.internal.net.server.AddAccessControlAllowOriginHeaderAfterResponseTest.java

private static HttpURLConnection connectToURL(String urlString, String method) throws Exception {
    final URL url = new URL(urlString);
    final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(method);
    connection.setDoOutput(true);/* w w w . j  a va  2 s .  c o  m*/
    connection.setConnectTimeout(1000);
    connection.connect();
    return connection;
}

From source file:Main.java

public static Bitmap downLoadBitmap(String httpUrl) {
    InputStream inputStream = null;
    try {//from   w w w .  j  av a 2s.c om
        URL url = new URL(httpUrl);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        conn.setReadTimeout(5000);
        conn.setConnectTimeout(5000);
        conn.connect();
        int responseCode = conn.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            inputStream = conn.getInputStream();

            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

            return bitmap;
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return null;
}

From source file:jfix.util.Urls.java

/**
 * Returns content from given url as string. The url can contain
 * username:password after the protocol, so that basic authorization is
 * possible./* ww  w . ja  va  2  s.c  o  m*/
 * 
 * Example for url with basic authorization:
 * 
 * http://username:password@www.domain.org/index.html
 */
public static String readString(String url, int timeout) {
    Reader reader = null;
    try {
        URLConnection uc = new URL(url).openConnection();
        if (uc instanceof HttpURLConnection) {
            HttpURLConnection httpConnection = (HttpURLConnection) uc;
            httpConnection.setConnectTimeout(timeout * 1000);
            httpConnection.setReadTimeout(timeout * 1000);
        }
        Matcher matcher = Pattern.compile("://(\\w+:\\w+)@").matcher(url);
        if (matcher.find()) {
            String auth = matcher.group(1);
            String encoding = Base64.getEncoder().encodeToString(auth.getBytes());
            uc.setRequestProperty("Authorization", "Basic " + encoding);
        }
        String charset = (uc.getContentType() != null && uc.getContentType().contains("charset="))
                ? uc.getContentType().split("charset=")[1]
                : "utf-8";
        reader = new BufferedReader(new InputStreamReader(uc.getInputStream(), charset));
        StringBuilder sb = new StringBuilder();
        for (int chr; (chr = reader.read()) != -1;) {
            sb.append((char) chr);
        }
        return sb.toString();
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }
    }
}

From source file:com.wabbit.libraries.remoting.HttpHelper.java

static public InputStream loadImage(String url) {
    HttpURLConnection connection = null;
    InputStream is = null;// w  w  w.j av  a2s .  c o m

    try {
        connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setConnectTimeout(20000);

        is = new BufferedInputStream(connection.getInputStream());
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }

    return is;
}

From source file:Main.java

static String downloadUrl(String myurl) throws IOException {
    InputStream is = null;//from ww w  .  j a  v a2s . c  o  m

    try {
        URL url = new URL(myurl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Authorization", "Basic cm9vdDpvcmllbnRkYg==");
        conn.setReadTimeout(10000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        //start
        conn.connect();
        int response = conn.getResponseCode();
        Log.e("The response is: ", "" + response);
        is = conn.getInputStream();
        //converte inputStream in stringa
        String contentAsString = readIt(is);
        return contentAsString;
    } catch (IOException e) {
        Log.e("HTTP", e.getMessage());
        return null;
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:com.nit.vicky.web.HttpFetcher.java

public static String downloadFileToSdCardMethod(String UrlToFile, Context context, String prefix, String method,
        Boolean isMP3) {/*from   ww w  . ja va2s  .  c om*/
    try {
        URL url = new URL(UrlToFile);

        String extension = ".mp3";

        if (!isMP3)
            extension = UrlToFile.substring(UrlToFile.lastIndexOf("."));

        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setConnectTimeout(10 * 1000);
        urlConnection.setReadTimeout(10 * 1000);
        urlConnection.setRequestMethod(method);
        //urlConnection.setRequestProperty("Referer", "http://mm.taobao.com/");
        urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");
        urlConnection.setRequestProperty("Accept", "*/*");
        urlConnection.connect();

        File file = File.createTempFile(prefix, extension, DiskUtil.getStoringDirectory());

        FileOutputStream fileOutput = new FileOutputStream(file);
        InputStream inputStream = urlConnection.getInputStream();

        byte[] buffer = new byte[1024];
        int bufferLength = 0;

        while ((bufferLength = inputStream.read(buffer)) > 0) {
            fileOutput.write(buffer, 0, bufferLength);
        }
        fileOutput.close();

        return file.getAbsolutePath();

    } catch (Exception e) {
        return "FAILED " + e.getMessage();
    }
}

From source file:Main.java

public static String customrequest(String url, HashMap<String, String> params, String method) {
    try {//from  w ww.  j  a va  2 s .  c  o  m

        URL postUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) postUrl.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setConnectTimeout(5 * 1000);

        conn.setRequestMethod(method);
        conn.setUseCaches(false);
        conn.setInstanceFollowRedirects(true);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)");

        conn.connect();
        OutputStream out = conn.getOutputStream();
        StringBuilder sb = new StringBuilder();
        if (null != params) {
            int i = params.size();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (i == 1) {
                    sb.append(entry.getKey() + "=" + entry.getValue());
                } else {
                    sb.append(entry.getKey() + "=" + entry.getValue() + "&");
                }

                i--;
            }
        }
        String content = sb.toString();
        out.write(content.getBytes("UTF-8"));
        out.flush();
        out.close();
        InputStream inStream = conn.getInputStream();
        String result = inputStream2String(inStream);
        conn.disconnect();
        return result;
    } catch (Exception e) {
        // TODO: handle exception
    }
    return null;
}