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.github.bmadecoder.Authenticator.java

public long getTimeDiff() {
    if (!this.syncing) {
        return 0;
    }/*  w ww .  ja  v  a2s  .c  o m*/
    try {
        URL url = URI.create("http://m.eu.mobileservice.blizzard.com/enrollment/time.htm").toURL();
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-type", "application/octet-stream");
        conn.setRequestProperty("Accept", "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2");
        conn.setReadTimeout(10000);
        conn.setDoInput(true);
        conn.connect();

        byte[] servertime = new byte[8];
        InputStream connectionStream = conn.getInputStream();
        connectionStream.read(servertime, 0, 8);
        connectionStream.close();
        conn.disconnect();

        return new BigInteger(servertime).longValue() - System.currentTimeMillis();
    } catch (MalformedURLException e) {
        throw new IllegalStateException(e);
    } catch (IOException e) {
        return 0;
    }
}

From source file:yulei.android.client.AndroidMobilePushApp.java

private String downloadUrl(String myurl) throws IOException {
    InputStream is = null;/*  www  .  ja  v a2 s.c o  m*/
    // 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(50000 /* milliseconds */);
        conn.setConnectTimeout(85000 /* milliseconds */);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        // Starts the query
        conn.connect();
        int response = conn.getResponseCode();
        Log.d(DEBUG_TAG, "The response is: " + response);
        is = conn.getInputStream();

        // Convert the InputStream into a string
        String contentAsString = readIt(is, len);
        return contentAsString;

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

From source file:cc.sferalabs.libs.telegram.bot.api.TelegramBot.java

/**
 * Sends a request to the server./*from w  w w. j ava  2 s  . c  o  m*/
 * 
 * @param <T>
 *            the class to cast the returned value to
 * @param request
 *            the request to be sent
 * @param timeout
 *            the read timeout value (in milliseconds) to be used for server
 *            response. A timeout of zero is interpreted as an infinite
 *            timeout
 * @return the JSON object representing the value of the field "result" of
 *         the response JSON object cast to the specified type parameter
 * @throws ResponseError
 *             if the server returned an error response, i.e. the value of
 *             the field "ok" of the response JSON object is {@code false}
 * @throws ParseException
 *             if an error occurs while parsing the server response
 * @throws IOException
 *             if an I/O exception occurs
 */
@SuppressWarnings("unchecked")
public <T> T sendRequest(Request request, int timeout) throws IOException, ParseException, ResponseError {
    HttpURLConnection connection = null;
    try {
        URL url = buildUrl(request);
        log.debug("Performing request: {}", url);
        connection = (HttpURLConnection) url.openConnection();
        connection.setReadTimeout(timeout);

        if (request instanceof SendFileRequest) {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            Path filePath = ((SendFileRequest) request).getFilePath();
            builder.addBinaryBody(((SendFileRequest) request).getFileParamName(), filePath.toFile());
            HttpEntity multipart = builder.build();

            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", multipart.getContentType().getValue());
            connection.setRequestProperty("Content-Length", "" + multipart.getContentLength());

            try (OutputStream out = connection.getOutputStream()) {
                multipart.writeTo(out);
            }
        } else {
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Content-Length", "0");
        }

        boolean httpOk = connection.getResponseCode() == HttpURLConnection.HTTP_OK;
        try (InputStream in = httpOk ? connection.getInputStream() : connection.getErrorStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8))) {
            JSONObject resp = (JSONObject) parser.parse(br);
            log.debug("Response: {}", resp);

            boolean ok = (boolean) resp.get("ok");
            if (!ok) {
                String description = (String) resp.get("description");
                if (description == null) {
                    description = "ok=false";
                }
                throw new ResponseError(description);
            }
            return (T) resp.get("result");
        }
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:it.greenvulcano.gvesb.adapter.http.mapping.ForwardHttpServletMapping.java

@SuppressWarnings("deprecation")
@Override/*from www .  j a v  a2s . c  o m*/
public void handleRequest(String methodName, HttpServletRequest req, HttpServletResponse resp)
        throws InboundHttpResponseException {

    logger.debug("BEGIN forward: " + req.getRequestURI());

    final HttpURLConnection httpConnection = (HttpURLConnection) connection;
    ;

    try {

        httpConnection.setRequestMethod(methodName);
        httpConnection.setReadTimeout(soTimeout);
        httpConnection.setDoInput(true);
        httpConnection.setDoOutput(true);

        if (dump) {
            StringBuffer sb = new StringBuffer();
            DumpUtils.dump(req, sb);
            logger.info(sb.toString());
        }

        String mapping = req.getPathInfo();
        if (mapping == null) {
            mapping = "/";
        }
        String destPath = contextPath + mapping;
        String queryString = req.getQueryString();
        if (queryString != null) {
            destPath += "?" + queryString;
        }
        if (!destPath.startsWith("/")) {
            destPath = "/" + destPath;
        }
        logger.info("Resulting QueryString: " + destPath);

        Collections.list(req.getHeaderNames()).forEach(headerName -> {
            httpConnection.setRequestProperty(headerName,
                    Collections.list(req.getHeaders(headerName)).stream().collect(Collectors.joining(";")));
        });

        if (methodName.equalsIgnoreCase("POST") || methodName.equalsIgnoreCase("PUT")) {
            httpConnection.setDoOutput(true);
            IOUtils.copy(req.getInputStream(), httpConnection.getOutputStream());

        }

        httpConnection.connect();
        int status = httpConnection.getResponseCode();

        resp.setStatus(status, httpConnection.getResponseMessage());

        httpConnection.getHeaderFields().entrySet().stream().forEach(header -> {
            resp.addHeader(header.getKey(), header.getValue().stream().collect(Collectors.joining(";")));
        });

        ByteArrayOutputStream bodyOut = new ByteArrayOutputStream();
        IOUtils.copy(httpConnection.getInputStream(), bodyOut);

        OutputStream out = resp.getOutputStream();
        out.write(bodyOut.toByteArray());
        //IOUtils.copy(method.getResponseBodyAsStream(), out);
        out.flush();
        out.close();

        if (dump) {
            StringBuffer sb = new StringBuffer();
            DumpUtils.dump(resp, bodyOut, sb);
            logger.info(sb.toString());
        }

    } catch (Exception exc) {
        logger.error("ERROR on forwarding: " + req.getRequestURI(), exc);
        throw new InboundHttpResponseException("GV_CALL_SERVICE_ERROR",
                new String[][] { { "message", exc.getMessage() } }, exc);
    } finally {
        try {
            if (httpConnection != null) {
                httpConnection.disconnect();
            }
        } catch (Exception exc) {
            logger.warn("Error while releasing connection", exc);
        }
        logger.debug("END forward: " + req.getRequestURI());
    }
}

From source file:br.gov.jfrj.siga.base.SigaHTTP.java

public String getNaWeb(String URL, HashMap<String, String> header, Integer timeout, String payload)
        throws AplicacaoException {

    try {//from w  w  w  .j  a  va 2s.c  o m

        HttpURLConnection conn = (HttpURLConnection) new URL(URL).openConnection();

        if (timeout != null) {
            conn.setConnectTimeout(timeout);
            conn.setReadTimeout(timeout);
        }

        //conn.setInstanceFollowRedirects(true);

        if (header != null) {
            for (String s : header.keySet()) {
                conn.setRequestProperty(s, header.get(s));
            }
        }

        System.setProperty("http.keepAlive", "false");

        if (payload != null) {
            byte ab[] = payload.getBytes("UTF-8");
            conn.setRequestMethod("POST");
            // Send post request
            conn.setDoOutput(true);
            OutputStream os = conn.getOutputStream();
            os.write(ab);
            os.flush();
            os.close();
        }

        //StringWriter writer = new StringWriter();
        //IOUtils.copy(conn.getInputStream(), writer, "UTF-8");
        //return writer.toString();
        return IOUtils.toString(conn.getInputStream(), "UTF-8");

    } catch (IOException ioe) {
        throw new AplicacaoException("No foi possvel abrir conexo", 1, ioe);
    }

}

From source file:com.example.ronald.tracle.MainActivity.java

private String downloadContent(String myurl) throws IOException {
    InputStream is = null;// w  ww.  j  a  va  2  s . com
    int length = 500;

    //SPECIAL CASE IN THIS ACTIIVTY
    String SITA_HOST = "flifo-qa.api.aero";
    // END OF SPECIAL PART

    try {
        URL url = new URL(myurl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("X-apiKey", SITA_KEY);
        conn.setRequestProperty("Host", SITA_HOST);
        conn.setDoInput(true);
        conn.connect();
        int response = conn.getResponseCode();
        Log.d(TAG, "The response is: " + response);
        is = conn.getInputStream();

        // Convert the InputStream into a string
        String contentAsString = convertInputStreamToString(is, length);
        return contentAsString;
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:com.forecast.io.toolbox.NetworkServiceTask.java

@Override
protected INetworkResponse doInBackground(INetworkRequest... params) {
    INetworkRequest request = params[0];

    if (request == null || isCancelled()) {
        return null;
    }/*  ww  w .j a  va2  s.co m*/

    InputStream input = null;

    BufferedOutputStream output = null;

    HttpURLConnection connection = null;

    INetworkResponse response = null;

    try {
        response = (INetworkResponse) request.getResponse().newInstance();

        URL url = new URL(request.getUri().toString());

        connection = (HttpURLConnection) url.openConnection();

        connection.setReadTimeout(SOCKET_TIME_OUT);

        connection.setConnectTimeout(CONNECTION_TIME_OUT);

        connection.setRequestMethod(request.getMethod().toString());

        connection.setDoInput(true);

        if (NetworkUtils.Method.POST.equals(request.getMethod())) {
            String data = request.getPostBody();

            if (data != null) {
                connection.setDoOutput(true);

                connection.setRequestProperty("Content-Type", request.getContentType());

                output = new BufferedOutputStream(connection.getOutputStream());

                output.write(data.getBytes());

                output.flush();

                IOUtils.closeQuietly(output);
            }
        }

        int code = connection.getResponseCode();

        input = (code != HttpStatus.SC_OK) ? connection.getErrorStream() : connection.getInputStream();

        response.onNetworkResponse(new JSONObject(IOUtils.toString(input)));

        IOUtils.closeQuietly(input);
    } catch (Exception e) {
        Log.e(Constants.LOG_TAG, e.toString());
    } finally {
        if (connection != null) {
            connection.disconnect();
        }

        IOUtils.closeQuietly(input);

        IOUtils.closeQuietly(output);
    }

    return response;
}

From source file:org.sufficientlysecure.keychain.keyimport.HkpKeyServer.java

private String query(String request) throws QueryException, HttpError {
    InetAddress ips[];//from  w  w w.j  a v  a  2 s.c o m
    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;
            Log.d(Constants.TAG, "hkp keyserver query: " + url);
            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:fr.cph.chicago.connection.CtaConnect.java

/**
 * Connect url/*from www . j a va 2  s  .  com*/
 *
 * @param address the address
 * @return the answer
 * @throws ConnectException
 */
@NonNull
private InputStream connectUrl(@NonNull final String address) throws ConnectException {
    final HttpURLConnection urlConnection;
    final InputStream inputStream;
    try {
        Log.v(TAG, "Address: " + address);
        final URL url = new URL(address);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setConnectTimeout(5000);
        urlConnection.setReadTimeout(5000);
        inputStream = new BufferedInputStream(urlConnection.getInputStream());
    } catch (final IOException e) {
        Log.e(TAG, e.getMessage(), e);
        throw new ConnectException(ConnectException.ERROR, e);
    }
    return inputStream;
}

From source file:org.thialfihar.android.apg.keyimport.HkpKeyserver.java

private String query(String request) throws QueryFailedException, HttpError {
    InetAddress ips[];/*from   w  ww.j a v a  2s .c  om*/
    try {
        ips = InetAddress.getAllByName(mHost);
    } catch (UnknownHostException e) {
        throw new QueryFailedException(e.toString());
    }
    for (int i = 0; i < ips.length; ++i) {
        try {
            String url = "http://" + ips[i].getHostAddress() + ":" + mPort + request;
            Log.d(Constants.TAG, "hkp keyserver query: " + url);
            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 QueryFailedException("querying server(s) for '" + mHost + "' failed");
}