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.jwrapper.maven.java.JavaDownloadMojo.java

protected HttpURLConnection connection(final String locationURL) throws Exception {

    final URL url = new URL(locationURL);

    final HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    connection.setUseCaches(false);/*from  w  ww.j av  a  2s . c om*/
    connection.setConnectTimeout(10 * 1000);
    connection.setInstanceFollowRedirects(true);

    for (final Map.Entry<String, String> entry : headerMap.entrySet()) {
        connection.setRequestProperty(entry.getKey(), entry.getValue());
    }

    connection.connect();

    return connection;

}

From source file:com.google.android.apps.santatracker.service.RemoteApiProcessor.java

/**
 * Downloads the given URL and return//from  w w w . ja  v  a  2  s . c  o m
 */
protected String downloadUrl(String myurl) throws IOException {
    InputStream is = null;
    // Only display the first 500 characters of the retrieved
    // web page content.
    // int len = 500;

    try {
        URL url = new URL(myurl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        // Starts the query
        conn.connect();
        int response = conn.getResponseCode();
        if (!isValidHeader(conn)) {
            // not a valid header
            Log.d(TAG, "Santa communication failure.");
            return null;

        } else if (response != 200) {
            Log.d(TAG, "Santa communication failure " + response);
            return null;

        } else {
            is = conn.getInputStream();

            // Convert the InputStream into a string
            return read(is).toString();
        }

        // Makes sure that the InputStream is closed
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:com.android.volley.toolbox.HurlStack.java

/**
 * Opens an {@link HttpURLConnection} with parameters.
 * @param url/*from  w w w .ja  va 2  s.  c  o m*/
 * @return an open connection
 * @throws IOException
 */
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
    HttpURLConnection connection = createConnection(url);

    int timeoutMs = request.getTimeoutMs();
    connection.setConnectTimeout(timeoutMs);
    connection.setReadTimeout(timeoutMs);
    connection.setUseCaches(false);
    connection.setDoInput(true);

    // use caller-provided custom SslSocketFactory, if any, for HTTPS
    if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
        ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory);
    }

    return connection;
}

From source file:com.epic.framework.implementation.tapjoy.TapjoyURLConnection.java

/**
 * Performs a network request call to the specified URL and parameters.
 * /*w  w  w  .  j a  va2s .  c  om*/
 * @param url                     The base URL.
 * @param params                  The URL parameters.
 * @return                         Response from the server.
 */
public String connectToURL(String url, String params) {
    String httpResponse = null;

    BufferedReader rd = null;
    StringBuilder sb = null;
    String line = null;

    try {
        String requestURL = url + params;

        // Replaces all spaces.
        requestURL = requestURL.replaceAll(" ", "%20");

        TapjoyLog.i(TAPJOY_URL_CONNECTION, "baseURL: " + url);
        TapjoyLog.i(TAPJOY_URL_CONNECTION, "requestURL: " + requestURL);

        // USE java.net HTTP connection instead.

        URL httpURL = new URL(requestURL);
        HttpURLConnection connection = (HttpURLConnection) httpURL.openConnection();
        connection.setConnectTimeout(15000);
        connection.setReadTimeout(30000);
        httpResponse = connection.getResponseMessage();

        connection.connect();

        // Read the result from the server.
        rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        sb = new StringBuilder();

        while ((line = rd.readLine()) != null) {
            sb.append(line + '\n');
        }

        httpResponse = sb.toString();

        // OLD CODE USING APACHE API

        // HttpGet http = new HttpGet(requestURL);
        //
        // // Create a HttpParams object so we can set our timeout times.
        // HttpParams httpParameters = new BasicHttpParams();
        //
        // // Time to wait to establish initial connection.
        // HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
        //
        // // Time to wait for incoming data.
        // HttpConnectionParams.setSoTimeout(httpParameters, 30000);
        //
        // // Create a http client with out timeout settings.
        // HttpClient client = new DefaultHttpClient(httpParameters);
        //
        // HttpResponse response = client.execute(http);
        // HttpEntity entity = response.getEntity();
        //
        // httpResponse = EntityUtils.toString(entity);

        TapjoyLog.i(TAPJOY_URL_CONNECTION, "--------------------");
        // TapjoyLog.i(TAPJOY_URL_CONNECTION, "response status: " + response.getStatusLine().getStatusCode());
        TapjoyLog.i(TAPJOY_URL_CONNECTION, "response size: " + httpResponse.length());
        TapjoyLog.i(TAPJOY_URL_CONNECTION, "response: ");
        TapjoyLog.i(TAPJOY_URL_CONNECTION, "" + httpResponse);
        TapjoyLog.i(TAPJOY_URL_CONNECTION, "--------------------");
    } catch (Exception e) {
        TapjoyLog.e(TAPJOY_URL_CONNECTION, "Exception: " + e.toString());
    }

    return httpResponse;
}

From source file:com.nxt.zyl.data.volley.toolbox.HurlStack.java

/**
 * Opens an {@link java.net.HttpURLConnection} with parameters.
 * @param url//  ww  w .j  ava 2 s  .  c o m
 * @return an open connection
 * @throws java.io.IOException
 */
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
    HttpURLConnection connection = createConnection(url);

    int timeoutMs = request.getTimeoutMs();
    connection.setConnectTimeout(CONNECTION_TIME_OUT_MS);
    connection.setReadTimeout(timeoutMs);
    connection.setUseCaches(false);
    connection.setDoInput(true);

    // use caller-provided custom SslSocketFactory, if any, for HTTPS
    if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
        ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory);
    }

    return connection;
}

From source file:org.openintents.openpgp.keyserver.HkpKeyServer.java

private String submitQuery(String request) throws QueryException, HttpError {
    InetAddress ips[];//from www  . java2s . c  om
    try {
        ips = InetAddress.getAllByName(mHost);
    } catch (UnknownHostException e) {
        throw new QueryException(e.toString());
    }
    for (int i = 0; i < ips.length; ++i) {
        try {
            String url = "http://" + ips[i].getHostAddress() + ":" + mPort + request;
            URL realUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(25000);
            conn.connect();
            int response = conn.getResponseCode();
            if (response >= 200 && response < 300) {
                return readAll(conn.getInputStream(), conn.getContentEncoding());
            } else {
                String data = readAll(conn.getErrorStream(), conn.getContentEncoding());
                throw new HttpError(response, data);
            }
        } catch (MalformedURLException e) {
            // nothing to do, try next IP
        } catch (IOException e) {
            // nothing to do, try next IP
        }
    }

    throw new QueryException("querying server(s) for '" + mHost + "' failed");
}

From source file:com.longwei.project.sso.client.util.HttpClient.java

public boolean isValidEndPoint(final URL url) {
    HttpURLConnection connection = null;
    try {/*w  ww.ja v a2  s  . c o m*/
        connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(this.connectionTimeout);
        connection.setReadTimeout(this.readTimeout);

        connection.connect();

        final int responseCode = connection.getResponseCode();

        for (final int acceptableCode : this.acceptableCodes) {
            if (responseCode == acceptableCode) {
                if (log.isDebugEnabled()) {
                    log.debug("Response code from server matched " + responseCode + ".");
                }
                return true;
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("Response Code did not match any of the acceptable response codes.  Code returned was "
                    + responseCode);
        }
    } catch (final IOException e) {
        log.error(e.getMessage(), e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
    return false;
}

From source file:mSearch.filmlisten.FilmlisteLesen.java

private InputStream getInputStreamForLocation(String source) throws IOException, URISyntaxException {
    InputStream in;//from   w  w w .  j  a  va  2s .  c  o  m
    long size = 0;
    final URI uri;
    if (source.startsWith("http")) {
        uri = new URI(source);
        //remote address for internet download
        HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();
        conn.setConnectTimeout(TIMEOUT);
        conn.setReadTimeout(TIMEOUT);
        conn.setRequestProperty("User-Agent", Config.getUserAgent());
        if (conn.getResponseCode() < 400) {
            size = conn.getContentLengthLong();
        }
        in = new ProgressMonitorInputStream(conn.getInputStream(), size, new InputStreamProgressMonitor() {
            private int oldProgress = 0;

            @Override
            public void progress(long bytesRead, long size) {
                final int iProgress = (int) (bytesRead * 100 / size);
                if (iProgress != oldProgress) {
                    oldProgress = iProgress;
                    notifyProgress(uri.toASCIIString(), "Download", iProgress);
                }
            }
        });
    } else {
        //local file
        notifyProgress(source, "Download", PROGRESS_MAX);
        in = new FileInputStream(source);
    }

    return in;
}

From source file:com.baseproject.volley.toolbox.HurlStack.java

/**
 * Opens an {@link HttpURLConnection} with parameters.
 * //from   w ww .j  a v  a 2s. co m
 * @param url
 * @return an open connection
 * @throws IOException
 */
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
    HttpURLConnection connection = createConnection(url);

    // int timeoutMs = request.getTimeoutMs();
    connection.setConnectTimeout(request.getConnTimeoutMs());
    connection.setReadTimeout(request.getReadTimeoutMs());
    connection.setUseCaches(false);
    connection.setDoInput(true);

    // use caller-provided custom SslSocketFactory, if any, for HTTPS
    if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
        ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory);
    }

    return connection;
}

From source file:com.external.volley.toolbox.HurlStack.java

/**
 * Opens an {@link HttpURLConnection} with parameters.
 * @param url//w  ww.ja v a 2s.  c o  m
 * @return an open connection
 * @throws IOException
 */
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {

    OkHttpClient okHttpClient = new OkHttpClient();
    HttpURLConnection connection = new OkUrlFactory(okHttpClient).open(url);

    int timeoutMs = request.getTimeoutMs();
    connection.setConnectTimeout(timeoutMs);
    connection.setReadTimeout(timeoutMs);
    connection.setUseCaches(false);
    connection.setDoInput(true);
    connection.setRequestProperty("Charset", "UTF-8"); // ?
    connection.setRequestProperty("connection", "keep-alive");

    // use caller-provided custom SslSocketFactory, if any, for HTTPS
    if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
        ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory);
    }

    return connection;
}