Example usage for java.net HttpURLConnection setReadTimeout

List of usage examples for java.net HttpURLConnection setReadTimeout

Introduction

In this page you can find the example usage for java.net HttpURLConnection setReadTimeout.

Prototype

public void setReadTimeout(int timeout) 

Source Link

Document

Sets the read timeout to a specified timeout, in milliseconds.

Usage

From source file:com.raphfrk.craftproxyclient.net.auth.AuthManager.java

@SuppressWarnings("unchecked")
public static void authServer16(String hash) throws IOException {
    URL url;/*from   w  w  w.  j a va 2s .  co m*/
    String username;
    String accessToken;
    try {
        if (loginDetails == null) {
            throw new IOException("Not logged in");
        }

        try {
            username = URLEncoder.encode(getUsername(), "UTF-8");
            accessToken = URLEncoder.encode(getAccessToken(), "UTF-8");
            hash = URLEncoder.encode(hash, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new IOException("Username/password encoding error", e);
        }

        String urlString;
        urlString = sessionServer16 + "user=" + username + "&sessionId=" + accessToken + "&serverId=" + hash;
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        throw new IOException("Auth server URL error", e);
    }
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setInstanceFollowRedirects(false);
    con.setReadTimeout(5000);
    con.setConnectTimeout(5000);
    con.connect();

    if (con.getResponseCode() != 200) {
        throw new IOException("Auth server rejected username and password");
    }

    BufferedReader reader = new BufferedReader(
            new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
    try {
        String reply = reader.readLine();
        if (!"OK".equals(reply)) {
            throw new IOException("Auth server replied (" + reply + ")");
        }
    } finally {
        reader.close();
        con.disconnect();
    }
}

From source file:com.magnet.tools.tests.MagnetToolStepDefs.java

public static boolean ping(String url, int maxSecs) {

    long startMs = System.currentTimeMillis();
    try {//www.j  a v  a 2 s .  c om
        while (maxSecs >= ((System.currentTimeMillis() - startMs) / 1000)) {
            try {
                HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
                connection.setConnectTimeout(5000);
                connection.setReadTimeout(5000);
                connection.setRequestMethod("GET");
                int responseCode = connection.getResponseCode();
                if (200 <= responseCode && responseCode <= 399) {
                    return true;
                } else {
                    Thread.sleep(2000);
                }
            } catch (IOException exception) {
                Thread.sleep(2000);
            }

        }
    } catch (InterruptedException ie) {
        // IGNORE
    }
    return false;
}

From source file:org.pixmob.fm2.util.HttpUtils.java

/**
 * Create a new Http connection for an URI.
 *//*w w  w.  j  a v a  2 s .  c o m*/
public static HttpURLConnection newRequest(Context context, String uri, Set<String> cookies)
        throws IOException {
    if (DEBUG) {
        Log.d(TAG, "Setup connection to " + uri);
    }

    final HttpURLConnection conn = (HttpURLConnection) new URL(uri).openConnection();
    conn.setUseCaches(false);
    conn.setInstanceFollowRedirects(false);
    conn.setConnectTimeout(30000);
    conn.setReadTimeout(60000);
    conn.setRequestProperty("Accept-Encoding", "gzip");
    conn.setRequestProperty("User-Agent", getUserAgent(context));
    conn.setRequestProperty("Cache-Control", "max-age=0");
    conn.setDoInput(true);

    // Close the connection when the request is done, or the application may
    // freeze due to a bug in some Android versions.
    conn.setRequestProperty("Connection", "close");

    if (conn instanceof HttpsURLConnection) {
        setupSecureConnection(context, (HttpsURLConnection) conn);
    }

    if (cookies != null && !cookies.isEmpty()) {
        final StringBuilder buf = new StringBuilder(256);
        for (final String cookie : cookies) {
            if (buf.length() != 0) {
                buf.append("; ");
            }
            buf.append(cookie);
        }
        conn.addRequestProperty("Cookie", buf.toString());
    }

    return conn;
}

From source file:com.magnet.plugin.common.helpers.URLHelper.java

public static InputStream loadUrl(final String url) throws Exception {
    final InputStream[] inputStreams = new InputStream[] { null };
    final Exception[] exception = new Exception[] { null };
    Future<?> downloadThreadFuture = ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
        public void run() {
            try {
                HttpURLConnection connection;
                if (ApplicationManager.getApplication() != null) {
                    connection = HttpConfigurable.getInstance().openHttpConnection(url);
                } else {
                    connection = (HttpURLConnection) new URL(url).openConnection();
                    connection.setReadTimeout(CONNECTION_TIMEOUT);
                    connection.setConnectTimeout(CONNECTION_TIMEOUT);
                }//from  ww  w.j a va 2s.c  o  m
                connection.connect();

                inputStreams[0] = connection.getInputStream();
            } catch (IOException e) {
                exception[0] = e;
            }
        }
    });

    try {
        downloadThreadFuture.get(5, TimeUnit.SECONDS);
    } catch (TimeoutException ignored) {
    }

    if (!downloadThreadFuture.isDone()) {
        downloadThreadFuture.cancel(true);
        throw new Exception(IdeBundle.message("updates.timeout.error"));
    }

    if (exception[0] != null)
        throw exception[0];
    return inputStreams[0];
}

From source file:net.andylizi.colormotd.utils.AttributionUtil.java

private static String sendGet(String url, String param, String charset) {
    StringBuilder result = new StringBuilder(1024);
    BufferedReader in = null;//  w w w .  j  a va2 s .co m
    try {
        String urlNameString = url + "?" + param;
        URL realUrl = new URL(urlNameString);
        HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
        conn.setRequestProperty("User-Agent", "ColorMOTD/" + UUID.randomUUID());
        conn.setRequestProperty("Accept-Charset", charset);
        conn.setUseCaches(true);
        conn.setConnectTimeout(2000);
        conn.setReadTimeout(3000);
        conn.connect();
        in = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.forName(charset)), 1024);
        String line;
        while ((line = in.readLine()) != null) {
            result.append(line);
        }
        conn.disconnect();
    } catch (Exception e) {
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (Exception e2) {
        }
    }
    return result.toString();
}

From source file:ee.ria.xroad.signer.certmanager.OcspClient.java

private static HttpURLConnection createConnection(URL url) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty(MimeUtils.HEADER_CONTENT_TYPE, MimeTypes.OCSP_REQUEST);
    connection.setRequestProperty("Accept", MimeTypes.OCSP_RESPONSE);
    connection.setDoOutput(true);//from   w  w  w .  java 2 s. c  o  m
    connection.setConnectTimeout(CONNECT_TIMEOUT_MS);
    connection.setReadTimeout(READ_TIMEOUT_MS);
    connection.connect();

    return connection;
}

From source file:com.polyvi.xface.http.XHttpWorker.java

/**
 * url???//from   w w w  . j  a v a2 s  .com
 *
 * @param url
 *            [in]
 * @return
 */
public static boolean isServerAccessable(String url) {
    boolean usable = false;
    try {
        URL urlCon = new URL(url);
        HttpURLConnection httpUrl = (HttpURLConnection) urlCon.openConnection();
        httpUrl.setConnectTimeout(SERVER_CONNECT_TIMEOUT);
        httpUrl.setReadTimeout(SERVER_CONNECT_TIMEOUT);
        if (httpUrl.getResponseCode() == HttpURLConnection.HTTP_OK) {
            usable = true;
            return usable;
        }
    } catch (IOException e) {
        usable = false;
        e.printStackTrace();
    }
    return usable;
}

From source file:Main.java

/**
 * On some devices we have to hack://  ww w .  jav  a2 s.co m
 * http://developers.sun.com/mobility/reference/techart/design_guidelines/http_redirection.html
 * @return the resolved url if any. Or null if it couldn't resolve the url
 * (within the specified time) or the same url if response code is OK
 */
public static String getResolvedUrl(String urlAsString, int timeout) {
    try {
        URL url = new URL(urlAsString);
        //using proxy may increase latency
        HttpURLConnection hConn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
        // force no follow

        hConn.setInstanceFollowRedirects(false);
        // the program doesn't care what the content actually is !!
        // http://java.sun.com/developer/JDCTechTips/2003/tt0422.html
        hConn.setRequestMethod("HEAD");
        // default is 0 => infinity waiting
        hConn.setConnectTimeout(timeout);
        hConn.setReadTimeout(timeout);
        hConn.connect();
        int responseCode = hConn.getResponseCode();
        hConn.getInputStream().close();
        if (responseCode == HttpURLConnection.HTTP_OK)
            return urlAsString;

        String loc = hConn.getHeaderField("Location");
        if (responseCode == HttpURLConnection.HTTP_MOVED_PERM && loc != null)
            return loc.replaceAll(" ", "+");

    } catch (Exception ex) {
    }
    return "";
}

From source file:com.vaguehope.onosendai.util.HttpHelper.java

private static <R> R fetchWithFollowRedirects(final Method method, final URL url,
        final HttpStreamHandler<R> streamHandler, final int redirectCount)
        throws IOException, URISyntaxException {
    final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    try {/* www .  j  a  v a 2s .  c o  m*/
        connection.setRequestMethod(method.toString());
        connection.setInstanceFollowRedirects(false);
        connection.setConnectTimeout((int) TimeUnit.SECONDS.toMillis(HTTP_CONNECT_TIMEOUT_SECONDS));
        connection.setReadTimeout((int) TimeUnit.SECONDS.toMillis(HTTP_READ_TIMEOUT_SECONDS));
        connection.setRequestProperty("User-Agent", "curl/1"); // Make it really clear this is not a browser.
        //connection.setRequestProperty("Accept-Encoding", "identity"); This fixes missing Content-Length headers but feels wrong.
        connection.connect();

        InputStream is = null;
        try {
            final int responseCode = connection.getResponseCode();

            // For some reason some devices do not follow redirects. :(
            if (responseCode == 301 || responseCode == 302 || responseCode == 303 || responseCode == 307) { // NOSONAR not magic numbers.  Its HTTP spec.
                if (redirectCount >= MAX_REDIRECTS)
                    throw new TooManyRedirectsException(responseCode, url, MAX_REDIRECTS);
                final String locationHeader = connection.getHeaderField("Location");
                if (locationHeader == null)
                    throw new HttpResponseException(responseCode,
                            "Location header missing.  Headers present: " + connection.getHeaderFields() + ".");
                connection.disconnect();

                final URL locationUrl;
                if (locationHeader.toLowerCase(Locale.ENGLISH).startsWith("http")) {
                    locationUrl = new URL(locationHeader);
                } else {
                    locationUrl = url.toURI().resolve(locationHeader).toURL();
                }
                return fetchWithFollowRedirects(method, locationUrl, streamHandler, redirectCount + 1);
            }

            if (responseCode < 200 || responseCode >= 300) { // NOSONAR not magic numbers.  Its HTTP spec.
                throw new NotOkResponseException(responseCode, connection, url);
            }

            is = connection.getInputStream();
            final int contentLength = connection.getContentLength();
            if (contentLength < 1)
                LOG.w("Content-Length=%s for %s.", contentLength, url);
            return streamHandler.handleStream(connection, is, contentLength);
        } finally {
            IoHelper.closeQuietly(is);
        }
    } finally {
        connection.disconnect();
    }
}

From source file:com.gson.util.HttpKit.java

/**
 * ?http?// w ww  . j a v a 2  s  . co m
 * @param url
 * @param method
 * @param headers
 * @return
 * @throws IOException
 */
private static HttpURLConnection initHttp(String url, String method, Map<String, String> headers)
        throws IOException {
    URL _url = new URL(url);
    HttpURLConnection http = (HttpURLConnection) _url.openConnection();
    // 
    http.setConnectTimeout(25000);
    // ? --??
    http.setReadTimeout(25000);
    http.setRequestMethod(method);
    http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    http.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
    if (null != headers && !headers.isEmpty()) {
        for (Entry<String, String> entry : headers.entrySet()) {
            http.setRequestProperty(entry.getKey(), entry.getValue());
        }
    }
    http.setDoOutput(true);
    http.setDoInput(true);
    http.connect();
    return http;
}