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:org.overlord.sramp.governance.shell.commands.Pkg2SrampCommand.java

/**
 * Returns true if the given URL can be accessed.
 * @param checkUrl/*  ww w . j a v  a  2s  . com*/
 * @param user
 * @param password
 */
public boolean urlExists(String checkUrl, String user, String password) {
    try {
        URL checkURL = new URL(checkUrl);
        HttpURLConnection checkConnection = (HttpURLConnection) checkURL.openConnection();
        checkConnection.setRequestMethod("GET"); //$NON-NLS-1$
        checkConnection.setRequestProperty("Accept", "application/xml"); //$NON-NLS-1$ //$NON-NLS-2$
        checkConnection.setConnectTimeout(10000);
        checkConnection.setReadTimeout(10000);
        applyAuth(checkConnection, user, password);
        checkConnection.connect();
        return (checkConnection.getResponseCode() == 200);
    } catch (Exception e) {
        return false;
    }
}

From source file:com.adaptris.core.http.client.net.StandardHttpProducer.java

private HttpURLConnection configureTimeouts(HttpURLConnection http, long timeout) {
    if (getConnectTimeout() != null) {
        http.setConnectTimeout(Long.valueOf(getConnectTimeout().toMilliseconds()).intValue());
    }/*ww  w  .j a  v  a  2s.c o  m*/
    if (getReadTimeout() != null) {
        http.setReadTimeout(Long.valueOf(getReadTimeout().toMilliseconds()).intValue());
    }
    if (timeout != DEFAULT_TIMEOUT) {
        http.setReadTimeout(Long.valueOf(timeout).intValue());
    }
    return http;
}

From source file:com.jaspersoft.jasperserver.api.engine.jasperreports.util.AwsEc2MetadataClient.java

private String readResource(String resourcePath) {
    HttpURLConnection connection = null;
    URL url = null;//from w ww. ja v a2  s . c o  m
    try {
        url = getEc2MetadataServiceUrlForResource(resourcePath);
        log.debug("Connecting to EC2 instance metadata service at URL: " + url.toString());
        connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(SECOND * 2);
        connection.setReadTimeout(SECOND * 7);
        connection.setRequestMethod("GET");
        connection.setDoOutput(true);
        connection.connect();

        if (connection.getResponseCode() >= HttpURLConnection.HTTP_OK
                && connection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {
            return readResponse(connection);
        } else {
            return null;
        }
    } catch (Exception e) {
        return null;
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:cm.aptoide.pt.util.NetworkUtils.java

public int checkServerConnection(final String string, final String username, final String password) {
    try {/*from ww  w  .j  a  v a  2s. c om*/

        HttpURLConnection client = (HttpURLConnection) new URL(string + "info.xml").openConnection();
        if (username != null && password != null) {
            String basicAuth = "Basic "
                    + new String(Base64.encode((username + ":" + password).getBytes(), Base64.NO_WRAP));
            client.setRequestProperty("Authorization", basicAuth);
        }
        client.setConnectTimeout(TIME_OUT);
        client.setReadTimeout(TIME_OUT);
        if (ApplicationAptoide.DEBUG_MODE)
            Log.i("Aptoide-NetworkUtils-checkServerConnection", "Checking on: " + client.getURL().toString());
        if (client.getContentType().equals("application/xml")) {
            return 0;
        } else {
            return client.getResponseCode();
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return -1;
}

From source file:com.google.ytd.picasa.PicasaApiHelper.java

public String getResumableUploadUrl(com.google.ytd.model.PhotoEntry photoEntry, String title,
        String description, String albumId, Double latitude, Double longitude) throws IllegalArgumentException {
    LOG.info(String.format("Resumable upload request.\nTitle: %s\nDescription: %s\nAlbum: %s", title,
            description, albumId));//from  w w  w.jav  a 2s.c  om

    // Picasa API resumable uploads are not currently documented publicly, but they're essentially
    // the same as what YouTube API offers:
    // http://code.google.com/apis/youtube/2.0/developers_guide_protocol_resumable_uploads.html
    // The Java client library does offer support for resumable uploads, but its use of threads
    // and some other assumptions makes it unsuitable for our purposes.
    try {
        URL url = new URL(String.format(RESUMABLE_UPLOADS_URL_FORMAT, albumId));
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setConnectTimeout(CONNECT_TIMEOUT);
        connection.setReadTimeout(READ_TIMEOUT);
        connection.setRequestMethod("POST");

        // Set all the GData request headers. These strings should probably be moved to CONSTANTS.
        connection.setRequestProperty("Content-Type", "application/atom+xml;charset=UTF-8");
        connection.setRequestProperty("Authorization",
                String.format("AuthSub token=\"%s\"", adminConfigDao.getAdminConfig().getPicasaAuthSubToken()));
        connection.setRequestProperty("GData-Version", "2.0");
        connection.setRequestProperty("Slug", photoEntry.getOriginalFileName());
        connection.setRequestProperty("X-Upload-Content-Type", photoEntry.getFormat());
        connection.setRequestProperty("X-Upload-Content-Length",
                String.valueOf(photoEntry.getOriginalFileSize()));

        // If we're given lat/long then create the element to geotag the picture; otherwise, pass in
        // and empty string for no geotag.
        String geoRss = "";
        if (latitude != null && longitude != null) {
            geoRss = String.format(GEO_RSS_XML_FORMAT, latitude, longitude);
            LOG.info("Geo RSS XML: " + geoRss);
        }

        String atomXml = String.format(UPLOAD_ENTRY_XML_FORMAT, StringEscapeUtils.escapeXml(title),
                StringEscapeUtils.escapeXml(description), geoRss);

        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
        writer.write(atomXml);
        writer.close();

        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            String uploadUrl = connection.getHeaderField("Location");
            if (util.isNullOrEmpty(uploadUrl)) {
                throw new IllegalArgumentException("No Location header found in HTTP response.");
            } else {
                LOG.info("Resumable upload URL is " + uploadUrl);

                return uploadUrl;
            }
        } else {
            LOG.warning(String.format("HTTP POST to %s returned status %d (%s).", url.toString(),
                    connection.getResponseCode(), connection.getResponseMessage()));
        }
    } catch (MalformedURLException e) {
        LOG.log(Level.WARNING, "", e);

        throw new IllegalArgumentException(e);
    } catch (IOException e) {
        LOG.log(Level.WARNING, "", e);
    }

    return null;
}

From source file:com.shenit.commons.utils.HttpUtils.java

/**
 * Proxy???/* www.j a  v  a2s .c  om*/
 * 
 * @param proxy
 *            Proxy
 * @param url
 */
public static long testProxy(Proxy proxy, URL url, int ctimeout, int rtimeout, int testTimes) {
    if (proxy == null)
        return -1;
    if (url == null) {
        try {
            url = new URL(DEFAULT_TEST_PROXY_URL);
        } catch (MalformedURLException e1) {
            LOG.warn("[testProxy] illegal url -> {}", url);
            return -1;
        }
    }
    HttpURLConnection conn = null;
    try {
        StopWatch watch = new StopWatch();
        watch.start();
        conn = (HttpURLConnection) url.openConnection(proxy);
        if (ctimeout > 0)
            conn.setConnectTimeout(ctimeout);
        if (rtimeout > 0)
            conn.setReadTimeout(rtimeout);
        long available = conn.getInputStream().available(); // try to get input
        int code = conn.getResponseCode();
        if (available < 1 || code != 200)
            return -1; //no content get
        watch.stop();
        return watch.getTime();
    } catch (Exception e) {
        LOG.warn("[testProxy] Could not connect to proxy -> {}", proxy.address());
        if (testTimes > 0)
            return testProxy(proxy, url, ctimeout, rtimeout, testTimes - 1);
    } finally {
        if (conn != null)
            IOUtils.close(conn);
    }
    return -1;
}

From source file:net.kourlas.voipms_sms.Api.java

private JSONObject getJson(String urlString) {
    try {/*from   w ww. jav  a  2 s .c  o m*/
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setReadTimeout(10000);
        connection.setConnectTimeout(15000);
        connection.setRequestMethod("GET");
        connection.setDoInput(true);
        connection.connect();

        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        StringBuilder data = new StringBuilder();
        String newLine = System.getProperty("line.separator");
        String line;
        while ((line = reader.readLine()) != null) {
            data.append(line);
            data.append(newLine);
        }
        reader.close();

        return new JSONObject(data.toString());
    } catch (MalformedURLException ex) {
        return null;
    } catch (IOException ex) {
        return null;
    } catch (JSONException ex) {
        return null;
    }
}

From source file:fr.mby.saml2.sp.opensaml.query.engine.SloRequestQueryProcessor.java

/**
 * Send the SLO Response via the URL Api.
 * /*from   w ww .j  a  v  a2 s. c  om*/
 * @param binding
 *            the binding to use
 * @param sloResponseRequest
 *            the SLO Response request
 */
protected void sendSloResponse(final SamlBindingEnum binding, final IOutgoingSaml sloResponseRequest) {
    URL sloUrl = null;
    HttpURLConnection sloConnexion = null;

    try {
        switch (binding) {
        case SAML_20_HTTP_REDIRECT:
            final String redirectUrl = sloResponseRequest.getHttpRedirectBindingUrl();

            sloUrl = new URL(redirectUrl);
            sloConnexion = (HttpURLConnection) sloUrl.openConnection();
            sloConnexion.setReadTimeout(10000);
            sloConnexion.connect();
            break;

        case SAML_20_HTTP_POST:
            final String sloEndpointUrl = sloResponseRequest.getEndpointUrl();
            final Collection<Entry<String, String>> sloPostParams = sloResponseRequest
                    .getHttpPostBindingParams();
            final StringBuffer samlDatas = new StringBuffer(1024);
            final Iterator<Entry<String, String>> itParams = sloPostParams.iterator();
            final Entry<String, String> firstParam = itParams.next();
            samlDatas.append(firstParam.getKey());
            samlDatas.append("=");
            samlDatas.append(firstParam.getValue());
            while (itParams.hasNext()) {
                final Entry<String, String> param = itParams.next();
                samlDatas.append("&");
                samlDatas.append(param.getKey());
                samlDatas.append("=");
                samlDatas.append(param.getValue());
            }

            sloUrl = new URL(sloEndpointUrl);
            sloConnexion = (HttpURLConnection) sloUrl.openConnection();
            sloConnexion.setDoInput(true);

            final OutputStreamWriter writer = new OutputStreamWriter(sloConnexion.getOutputStream());
            writer.write(samlDatas.toString());
            writer.flush();
            writer.close();

            sloConnexion.setReadTimeout(10000);
            sloConnexion.connect();
            break;

        default:
            break;
        }

        if (sloConnexion != null) {
            final InputStream responseStream = sloConnexion.getInputStream();

            final StringWriter writer = new StringWriter();
            IOUtils.copy(responseStream, writer, "UTF-8");
            final String response = writer.toString();

            this.logger.debug(String.format("HTTP response to SLO Request sent: [%s] ", response));

            final int responseCode = sloConnexion.getResponseCode();

            final String samlMessage = sloResponseRequest.getSamlMessage();
            final String endpointUrl = sloResponseRequest.getEndpointUrl();
            if (responseCode < 0) {
                this.logger.error("Unable to send SAML 2.0 Single Logout Response [{}] to endpoint URL [{}] !",
                        samlMessage, endpointUrl);
            } else if (responseCode == 200) {
                this.logger.info("SAML 2.0 Single Logout Request correctly sent to [{}] !", endpointUrl);
            } else {
                this.logger.error(
                        "HTTP response code: [{}] ! Error while sending SAML 2.0 Single Logout Request [{}] to endpoint URL [{}] !",
                        new Object[] { responseCode, samlMessage, endpointUrl });
            }
        }

    } catch (final MalformedURLException e) {
        this.logger.error(String.format("Malformed SAML SLO request URL: [%s] !", sloUrl.toExternalForm()), e);
    } catch (final IOException e) {
        this.logger.error(String.format("Unable to send SAML SLO request URL: [%s] !", sloUrl.toExternalForm()),
                e);
    } finally {
        sloConnexion.disconnect();
    }
}

From source file:org.jmxtrans.embedded.config.EtcdKVStore.java

private String httpGET(URL base, String key) {

    InputStream is = null;/*w  ww  . jav  a2 s . co  m*/
    HttpURLConnection conn = null;
    String json = null;
    try {
        URL url = new URL(base + "/v2/keys/" + key);
        conn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(2000);
        conn.setReadTimeout(2000);

        conn.connect();
        int respCode = conn.getResponseCode();

        if (respCode == 404) {
            return null;
        } else if (respCode > 400) {
            return HTTP_ERR;
        }

        is = conn.getInputStream();
        String contentEncoding = conn.getContentEncoding() != null ? conn.getContentEncoding() : "UTF-8";
        json = IOUtils.toString(is, contentEncoding);
    } catch (MalformedURLException e) {
        json = HTTP_ERR;
        // nothing to do, try next server
    } catch (ProtocolException e) {
        // nothing to do, try next server
        json = HTTP_ERR;
    } catch (IOException e) {
        // nothing to do, try next server
        json = HTTP_ERR;
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                // nothing to do, try next server
            }
        }
        if (conn != null) {
            conn.disconnect();
        }
    }

    return json;
}