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.dianping.phoenix.dev.core.tools.generator.stable.GitRepositoryListGenerator.java

private static String curl(String url) throws Exception {
    URL reqUrl = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) reqUrl.openConnection();
    conn.setRequestMethod("GET");
    conn.setConnectTimeout(3000);
    System.out.println(url);/* w w w  .j a  va 2  s  .  co  m*/
    return IOUtils.toString(new InputStreamReader(conn.getInputStream(), "UTF-8"));
}

From source file:Main.java

public static boolean selectServer() {
    boolean status = false;
    for (String host : host_arr) {
        String str = host + Servlet_phone;
        HttpURLConnection conn = null;
        try {// w  ww.j  ava2 s. c  o m
            conn = (HttpURLConnection) new URL(str).openConnection();
            conn.setConnectTimeout(4000);
            int result = conn.getResponseCode();
            if (result == HttpURLConnection.HTTP_OK) {
                HOST = str;//
                HOST_PORT = host;
                status = true;
                break;
            } else {
            }
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        } finally {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
        }
    }
    return status;
}

From source file:com.dianping.phoenix.dev.core.tools.generator.stable.GitRepositoryListGenerator.java

private static int curl_code(String url) throws Exception {
    URL reqUrl = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) reqUrl.openConnection();
    conn.setRequestMethod("GET");
    conn.setConnectTimeout(3000);

    conn.setRequestProperty("Cookie",
            "uid=code51c3bceea328e0.87696853; remember_user_token=BAhbB1sGaXFJIiIkMmEkMTAkQUR2YXNENGNqT2NSaDBvVWRSS2guTwY6BkVU--bd148a50388e51e524e89809afd6d98e69793711; request_method=GET; _gitlab_session=BAh7CEkiD3Nlc3Npb25faWQGOgZFRkkiJTMzY2U3YzM3YjlhZWQ1ODcwNDljNDA0MjFkOTdjZjA4BjsAVEkiEF9jc3JmX3Rva2VuBjsARkkiMTNqS1V3V2paUCtCWU0rbVZtTUVraFBpTDR3MGFpZ2FtaExXeWphYjJRSVE9BjsARkkiGXdhcmRlbi51c2VyLnVzZXIua2V5BjsAVFsHWwZpcUkiIiQyYSQxMCRBRHZhc0Q0Y2pPY1JoMG9VZFJLaC5PBjsAVA%3D%3D--af5d6859bcba9e86e72ca6c3b2430400db75dcad");
    return conn.getResponseCode();
}

From source file:Main.java

public static boolean isConnectionAvailable() {
    class NetworkCheckTask extends AsyncTask<Void, Void, Boolean> {

        @Override/* ww w  . j ava  2 s  . c  o  m*/
        protected Boolean doInBackground(Void... params) {
            try {
                URL url = new URL(MAD_SERVER + "/sync.html");
                HttpURLConnection conn = null;
                conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(999);
                conn.setRequestMethod("GET");
                conn.setDoInput(true);
                conn.connect();
                if (conn.getResponseCode() == 200)
                    return true;
                else
                    return false;
            } catch (Exception e) {
                return false;
            }
        }

    }

    try {
        NetworkCheckTask async = new NetworkCheckTask();
        async.execute();
        return async.get();
    } catch (Exception e) {
        return false;
    }
}

From source file:Main.java

public static String UpdateScore(String userName, int br) {

    String retStr = "";

    try {//from ww w .j  a v  a  2  s.  com
        URL url = new URL("http://" + IP_ADDRESS + "/RiddleQuizApp/ServerSide/AzurirajHighScore.php");

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(15000);
        conn.setReadTimeout(10000);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);
        Log.e("http", "por1");

        JSONObject data = new JSONObject();

        data.put("username", userName);
        data.put("broj", br);

        Log.e("http", "por3");

        Uri.Builder builder = new Uri.Builder().appendQueryParameter("action", data.toString());
        String query = builder.build().getEncodedQuery();

        Log.e("http", "por4");

        OutputStream os = conn.getOutputStream();
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        bw.write(query);
        Log.e("http", "por5");
        bw.flush();
        bw.close();
        os.close();
        int responseCode = conn.getResponseCode();

        Log.e("http", String.valueOf(responseCode));
        if (responseCode == HttpURLConnection.HTTP_OK) {
            retStr = inputStreamToString(conn.getInputStream());
        } else
            retStr = String.valueOf("Error: " + responseCode);

        Log.e("http", retStr);

    } catch (Exception e) {
        Log.e("http", "greska");
    }
    return retStr;
}

From source file:Main.java

public static String UdatePlayerBT(String userName, String device) {

    String retStr = "";

    try {/*from w w w. j  ava2 s . c  o m*/
        URL url = new URL("http://" + IP_ADDRESS + "/RiddleQuizApp/ServerSide/PostaviBTdevice.php");

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(15000);
        conn.setReadTimeout(10000);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        Log.e("http", "por1");

        JSONObject data = new JSONObject();

        data.put("username", userName);
        data.put("bt_device", device);

        Log.e("http", "por3");

        Uri.Builder builder = new Uri.Builder().appendQueryParameter("action", data.toString());
        String query = builder.build().getEncodedQuery();

        Log.e("http", "por4");

        OutputStream os = conn.getOutputStream();
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        bw.write(query);
        Log.e("http", "por5");
        bw.flush();
        bw.close();
        os.close();
        int responseCode = conn.getResponseCode();

        Log.e("http", String.valueOf(responseCode));
        if (responseCode == HttpURLConnection.HTTP_OK) {
            retStr = inputStreamToString(conn.getInputStream());
        } else
            retStr = String.valueOf("Error: " + responseCode);

        Log.e("http", retStr);

    } catch (Exception e) {
        Log.e("http", "greska");
    }
    return retStr;
}

From source file:Main.java

public static Document getUrlAsDocument(String urlAsString, int timeout) throws Exception {
    URL url = new URL(urlAsString);
    //using proxy may increase latency
    HttpURLConnection hConn = (HttpURLConnection) url.openConnection();
    hConn.setReadTimeout(timeout);// w ww .  ja v  a2 s . com
    hConn.setConnectTimeout(timeout);
    //        hConn.setRequestProperty("Accept-Encoding", "gzip, deflate");

    InputStream is = hConn.getInputStream();
    //        if ("gzip".equals(hConn.getContentEncoding()))
    //            is = new GZIPInputStream(is);
    return newDocumentBuilder().parse(is);
}

From source file:Main.java

/**
 * Given a string url, connects and returns response code
 *
 * @param urlString       string to fetch
 * @param network       network/*w w  w.  j a  va 2  s  .  co m*/
 * @param readTimeOutMs       read time out
 * @param connectionTimeOutMs       connection time out
 * @param urlRedirect       should use urlRedirect
 * @param useCaches       should use cache
 * @return httpResponseCode http response code
 * @throws IOException
 */

@TargetApi(LOLLIPOP)
public static int checkUrlWithOptionsOverNetwork(String urlString, Network network, int readTimeOutMs,
        int connectionTimeOutMs, boolean urlRedirect, boolean useCaches) throws IOException {
    if (network == null) {
        return -1;
    }
    URL url = new URL(urlString);
    HttpURLConnection connection = (HttpURLConnection) network.openConnection(url);
    connection.setReadTimeout(readTimeOutMs /* milliseconds */);
    connection.setConnectTimeout(connectionTimeOutMs /* milliseconds */);
    connection.setRequestMethod("GET");
    connection.setInstanceFollowRedirects(urlRedirect);
    connection.setUseCaches(useCaches);
    // Starts the query
    connection.connect();
    int responseCode = connection.getResponseCode();
    connection.disconnect();
    return responseCode;
}

From source file:Main.java

static public InputStream loadImage(String url) {
    HttpURLConnection connection = null;
    InputStream is = null;//from  w w  w.j  a  v  a  2s. co  m

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

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

    return is;
}

From source file:Main.java

private static String getStringFromUrl(String url, int connectTimeout, int readTimeout)
        throws MalformedURLException, JSONException, IOException {
    URL urlObject = new URL(url);
    HttpURLConnection urlConn = (HttpURLConnection) urlObject.openConnection();
    String jsonString = "";

    if (connectTimeout != 0) {
        urlConn.setConnectTimeout(connectTimeout);
    }/*  w w  w.  ja  v a2 s.c om*/
    if (readTimeout != 0) {
        urlConn.setReadTimeout(readTimeout);
    }

    try {
        jsonString = getStringFromInputStream(urlConn.getInputStream());
    } finally {
        urlConn.disconnect();
    }
    return jsonString;
}