Example usage for java.net URLConnection setReadTimeout

List of usage examples for java.net URLConnection setReadTimeout

Introduction

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

Prototype

public void setReadTimeout(int timeout) 

Source Link

Document

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

Usage

From source file:net.technicpack.rest.RestObject.java

public static <T> List<T> getRestArray(Class<T> restObject, String url) throws RestfulAPIException {
    InputStream stream = null;//from ww w  . ja v  a 2 s  .  c  om
    try {
        URLConnection conn = new URL(url).openConnection();
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
        conn.setConnectTimeout(15000);
        conn.setReadTimeout(15000);

        stream = conn.getInputStream();
        String data = IOUtils.toString(stream, Charsets.UTF_8);

        JsonElement response = gson.fromJson(data, JsonElement.class);

        if (response == null || !response.isJsonArray()) {
            if (response.isJsonObject() && response.getAsJsonObject().has("error"))
                throw new RestfulAPIException("Error in response: " + response.getAsJsonObject().get("error"));
            else
                throw new RestfulAPIException("Unable to access URL [" + url + "]");
        }

        JsonArray array = response.getAsJsonArray();
        List<T> result = new ArrayList<T>(array.size());

        for (JsonElement element : array) {
            if (element.isJsonObject())
                result.add(gson.fromJson(element.getAsJsonObject(), restObject));
            else
                result.add(gson.fromJson(element.getAsString(), restObject));
        }

        return result;
    } catch (SocketTimeoutException e) {
        throw new RestfulAPIException("Timed out accessing URL [" + url + "]", e);
    } catch (MalformedURLException e) {
        throw new RestfulAPIException("Invalid URL [" + url + "]", e);
    } catch (JsonParseException e) {
        throw new RestfulAPIException("Error parsing response JSON at URL [" + url + "]", e);
    } catch (IOException e) {
        throw new RestfulAPIException("Error accessing URL [" + url + "]", e);
    } finally {
        IOUtils.closeQuietly(stream);
    }
}

From source file:org.apache.niolex.commons.net.HTTPUtil.java

/**
 * Do the HTTP request./*  ww w .j  av  a  2  s .  com*/
 *
 * @param strUrl the request URL
 * @param params the request parameters
 * @param paramCharset the charset used to send the request parameters
 * @param headers the request headers
 * @param connectTimeout the connection timeout
 * @param readTimeout the data read timeout
 * @param useGet whether do we use the HTTP GET method
 * @return the response pair; a is response header map, b is response body
 * @throws NetException
 */
public static final Pair<Map<String, List<String>>, byte[]> doHTTP(String strUrl, Map<String, String> params,
        String paramCharset, Map<String, String> headers, int connectTimeout, int readTimeout, boolean useGet)
        throws NetException {
    LOG.debug("Start HTTP {} request to [{}], C{}R{}.", useGet ? "GET" : "POST", strUrl, connectTimeout,
            readTimeout);
    InputStream in = null;
    try {
        // 1. For get, we pass parameters in URL; for post, we save it in reqBytes.
        byte[] reqBytes = null;
        if (!CollectionUtil.isEmpty(params)) {
            if (useGet) {
                strUrl = strUrl + '?' + prepareWwwFormUrlEncoded(params, paramCharset);
            } else {
                reqBytes = StringUtil.strToAsciiByte(prepareWwwFormUrlEncoded(params, paramCharset));
            }
        }
        URL url = new URL(strUrl); // We use Java URL to do the HTTP request.
        URLConnection ucon = url.openConnection();
        ucon.setConnectTimeout(connectTimeout);
        ucon.setReadTimeout(readTimeout);
        // 2. validate to Connection type.
        if (!(ucon instanceof HttpURLConnection)) {
            throw new NetException(NetException.ExCode.INVALID_URL_TYPE,
                    "The request is not in HTTP protocol.");
        }
        final HttpURLConnection httpCon = (HttpURLConnection) ucon;
        // 3. We add all the request headers.
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpCon.addRequestProperty(entry.getKey(), entry.getValue());
            }
        }
        // 4. For get or no parameter, we do not output data; for post, we pass parameters in Body.
        if (reqBytes == null) {
            httpCon.setDoOutput(false);
        } else {
            httpCon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpCon.setRequestProperty("Content-Length", Integer.toString(reqBytes.length));
            httpCon.setRequestMethod("POST");
            httpCon.setDoOutput(true);
        }
        httpCon.setDoInput(true);
        httpCon.connect();
        // 5. do output if needed.
        if (reqBytes != null) {
            StreamUtil.writeAndClose(httpCon.getOutputStream(), reqBytes);
        }
        // 6. Get the input stream.
        in = httpCon.getInputStream();
        final int contentLength = httpCon.getContentLength();
        validateHttpCode(strUrl, httpCon);
        byte[] ret = null;
        // 7. Read response byte array according to the strategy.
        if (contentLength > 0) {
            ret = commonDownload(contentLength, in);
        } else {
            ret = unusualDownload(strUrl, in, MAX_BODY_SIZE, true);
        }
        // 8. Parse the response headers.
        LOG.debug("Succeeded to execute HTTP request to [{}], response size {}.", strUrl, ret.length);
        return Pair.create(httpCon.getHeaderFields(), ret);
    } catch (NetException e) {
        LOG.info(e.getMessage());
        throw e;
    } catch (Exception e) {
        String msg = "Failed to execute HTTP request to [" + strUrl + "], msg=" + e.toString();
        LOG.warn(msg);
        throw new NetException(NetException.ExCode.IOEXCEPTION, msg, e);
    } finally {
        // Close the input stream.
        StreamUtil.closeStream(in);
    }
}

From source file:com.qweex.callisto.moar.twit.java

public static String callURL(String myURL) {
    StringBuilder sb = new StringBuilder();
    URLConnection urlConn = null;
    InputStreamReader in = null;//from  ww  w .j  a  va 2s . c om
    try {
        URL url = new URL(myURL);
        urlConn = url.openConnection();
        if (urlConn != null)
            urlConn.setReadTimeout(60 * 1000);
        if (urlConn != null && urlConn.getInputStream() != null) {
            in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());
            BufferedReader bufferedReader = new BufferedReader(in);
            if (bufferedReader != null) {
                int cp;
                while ((cp = bufferedReader.read()) != -1) {
                    sb.append((char) cp);
                }
                bufferedReader.close();
            }
        }
        in.close();
    } catch (Exception e) {
        throw new RuntimeException("Exception while calling URL:" + myURL, e);
    }

    return sb.toString();
}

From source file:org.apache.maven.report.projectinfo.ProjectInfoReportUtils.java

/**
 * @param url not null//from  w  w  w  . j  a va2 s.  c  o m
 * @param project not null
 * @param settings not null
 * @return the url connection with auth if required. Don't check the certificate if SSL scheme.
 * @throws IOException if any
 */
private static URLConnection getURLConnection(URL url, MavenProject project, Settings settings)
        throws IOException {
    URLConnection conn = url.openConnection();
    conn.setConnectTimeout(TIMEOUT);
    conn.setReadTimeout(TIMEOUT);

    // conn authorization
    if (settings.getServers() != null && !settings.getServers().isEmpty() && project != null
            && project.getDistributionManagement() != null
            && (project.getDistributionManagement().getRepository() != null
                    || project.getDistributionManagement().getSnapshotRepository() != null)
            && (StringUtils.isNotEmpty(project.getDistributionManagement().getRepository().getUrl())
                    || StringUtils.isNotEmpty(
                            project.getDistributionManagement().getSnapshotRepository().getUrl()))) {
        Server server = null;
        if (url.toString().contains(project.getDistributionManagement().getRepository().getUrl())) {
            server = settings.getServer(project.getDistributionManagement().getRepository().getId());
        }
        if (server == null && url.toString()
                .contains(project.getDistributionManagement().getSnapshotRepository().getUrl())) {
            server = settings.getServer(project.getDistributionManagement().getSnapshotRepository().getId());
        }

        if (server != null && StringUtils.isNotEmpty(server.getUsername())
                && StringUtils.isNotEmpty(server.getPassword())) {
            String up = server.getUsername().trim() + ":" + server.getPassword().trim();
            String upEncoded = new String(Base64.encodeBase64Chunked(up.getBytes())).trim();

            conn.setRequestProperty("Authorization", "Basic " + upEncoded);
        }
    }

    if (conn instanceof HttpsURLConnection) {
        HostnameVerifier hostnameverifier = new HostnameVerifier() {
            /** {@inheritDoc} */
            public boolean verify(String urlHostName, SSLSession session) {
                return true;
            }
        };
        ((HttpsURLConnection) conn).setHostnameVerifier(hostnameverifier);

        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            /** {@inheritDoc} */
            public void checkClientTrusted(final X509Certificate[] chain, final String authType) {
            }

            /** {@inheritDoc} */
            public void checkServerTrusted(final X509Certificate[] chain, final String authType) {
            }

            /** {@inheritDoc} */
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };

        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new SecureRandom());

            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            ((HttpsURLConnection) conn).setSSLSocketFactory(sslSocketFactory);
        } catch (NoSuchAlgorithmException e1) {
            // ignore
        } catch (KeyManagementException e) {
            // ignore
        }
    }

    return conn;
}

From source file:com.comcast.cdn.traffic_control.traffic_monitor.util.Fetcher.java

public static String fetchContent(final URLConnection conn, final int timeout) throws IOException {
    conn.setAllowUserInteraction(true);/*  ww w  . j  av  a2 s.  c  om*/
    if (timeout != 0) {
        conn.setConnectTimeout(timeout);
        conn.setReadTimeout(timeout);
    }
    conn.connect();
    return IOUtils.toString(new InputStreamReader(conn.getInputStream(), UTF8_STR));
}

From source file:com.bt.download.android.gui.transfers.HttpDownload.java

static void simpleHTTP(String url, OutputStream out, int timeout) throws Throwable {
    URL u = new URL(url);
    URLConnection con = u.openConnection();
    con.setConnectTimeout(timeout);/* w  w w .  j a  va  2  s. c o  m*/
    con.setReadTimeout(timeout);
    InputStream in = con.getInputStream();
    try {

        byte[] b = new byte[1024];
        int n = 0;
        while ((n = in.read(b, 0, b.length)) != -1) {
            out.write(b, 0, n);
        }
    } finally {
        try {
            out.close();
        } catch (Throwable e) {
            // ignore   
        }
        try {
            in.close();
        } catch (Throwable e) {
            // ignore   
        }
    }
}

From source file:xtrememp.update.SoftwareUpdate.java

public static Version getLastVersion(URL url) throws Exception {
    Version result = null;//  w w  w  .ja  va 2 s.  c o m
    InputStream urlStream = null;
    try {
        URLConnection urlConnection = url.openConnection();
        urlConnection.setAllowUserInteraction(false);
        urlConnection.setConnectTimeout(30000);
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(false);
        urlConnection.setReadTimeout(10000);
        urlConnection.setUseCaches(true);
        urlStream = urlConnection.getInputStream();
        Properties properties = new Properties();
        properties.load(urlStream);

        result = new Version();
        result.setMajorNumber(Integer.parseInt(properties.getProperty("xtrememp.lastVersion.majorNumber")));
        result.setMinorNumber(Integer.parseInt(properties.getProperty("xtrememp.lastVersion.minorNumber")));
        result.setMicroNumber(Integer.parseInt(properties.getProperty("xtrememp.lastVersion.microNumber")));
        result.setVersionType(
                Version.VersionType.valueOf(properties.getProperty("xtrememp.lastVersion.versionType")));
        result.setReleaseDate(properties.getProperty("xtrememp.lastVersion.releaseDate"));
        result.setDownloadURL(properties.getProperty("xtrememp.lastVersion.dounloadURL"));
    } finally {
        IOUtils.closeQuietly(urlStream);
    }
    return result;
}

From source file:savant.util.NetworkUtils.java

/**
 * Open a stream for the given URL with the CONNECT_TIMEOUT and READ_TIMEOUT.
 * @throws IOException/*from  ww w  .  ja  va2 s. co  m*/
 */
public static InputStream openStream(URL url) throws IOException {
    URLConnection conn = url.openConnection();
    conn.setConnectTimeout(CONNECT_TIMEOUT);
    conn.setReadTimeout(READ_TIMEOUT);
    return conn.getInputStream();
}

From source file:com.frostwire.transfers.BaseHttpDownload.java

static void simpleHTTP(String url, OutputStream out, int timeout) throws Throwable {
    URL u = new URL(url);
    URLConnection con = u.openConnection();
    con.setConnectTimeout(timeout);//from   ww w  .  j a va2  s.c om
    con.setReadTimeout(timeout);
    InputStream in = con.getInputStream();
    try {

        byte[] b = new byte[1024];
        int n = 0;
        while ((n = in.read(b, 0, b.length)) != -1) {
            out.write(b, 0, n);
        }
    } finally {
        try {
            out.close();
        } catch (Throwable e) {
            // ignore
        }
        try {
            in.close();
        } catch (Throwable e) {
            // ignore
        }
    }
}

From source file:com.entertailion.android.shapeways.api.ShapewaysClient.java

/**
 * Utility method to create a URL connection
 * /*from   w  w w .j a va2 s. c o  m*/
 * @param urlValue
 * @param doPost
 *            is this for a HTTP POST
 * @return
 * @throws Exception
 */
private static URLConnection getUrlConnection(String urlValue, boolean doPost) throws Exception {
    URL url = new URL(urlValue);
    URLConnection urlConnection = url.openConnection();
    urlConnection.setConnectTimeout(0);
    urlConnection.setReadTimeout(0);
    if (doPost) {
        urlConnection.setDoOutput(true);
    }
    return urlConnection;
}