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.offbynull.portmapper.upnpigd.UpnpIgdController.java

private Map<String, String> performRequest(String action, ImmutablePair<String, String>... params) {
    byte[] outgoingData = createRequestXml(action, params);

    HttpURLConnection conn = null;

    try {//  ww w . j  a v a2  s. c  o  m
        URL url = controlUrl.toURL();
        conn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);

        conn.setRequestMethod("POST");
        conn.setReadTimeout(3000);
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "text/xml");
        conn.setRequestProperty("SOAPAction", serviceType + "#" + action);
        conn.setRequestProperty("Connection", "Close");
    } catch (IOException ex) {
        throw new IllegalStateException(ex); // should never happen
    }

    try (OutputStream os = conn.getOutputStream()) {
        os.write(outgoingData);
    } catch (IOException ex) {
        IOUtils.close(conn);
        throw new ResponseException(ex);
    }

    byte[] incomingData;
    int respCode;
    try {
        respCode = conn.getResponseCode();
    } catch (IOException ioe) {
        IOUtils.close(conn);
        throw new ResponseException(ioe);
    }

    if (respCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
        try (InputStream is = conn.getErrorStream()) {
            incomingData = IOUtils.toByteArray(is);
        } catch (IOException ex) {
            IOUtils.close(conn);
            throw new ResponseException(ex);
        }
    } else {
        try (InputStream is = conn.getInputStream()) {
            incomingData = IOUtils.toByteArray(is);
        } catch (IOException ex) {
            IOUtils.close(conn);
            throw new ResponseException(ex);
        }
    }

    return parseResponseXml(action + "Response", incomingData);
}

From source file:org.jmxtrans.embedded.output.LibratoWriter.java

/**
 * Send given metrics to the Graphite server.
 *//*from ww w .  j  ava  2 s  . co m*/
@Override
public void write(Iterable<QueryResult> results) {
    logger.debug("Export to '{}', proxy {} metrics {}", url, proxy, results);

    List<QueryResult> counters = new ArrayList<QueryResult>();
    List<QueryResult> gauges = new ArrayList<QueryResult>();
    for (QueryResult result : results) {
        if (METRIC_TYPE_GAUGE.equals(result.getType())) {
            gauges.add(result);
        } else if (METRIC_TYPE_COUNTER.equals(result.getType())) {
            counters.add(result);
        } else if (null == result.getType()) {
            logger.info("Unspecified type for result {}, export it as counter");
            counters.add(result);
        } else {
            logger.info("Unsupported metric type '{}' for result {}, export it as counter", result.getType(),
                    result);
            counters.add(result);
        }
    }

    HttpURLConnection urlConnection = null;
    try {
        if (proxy == null) {
            urlConnection = (HttpURLConnection) url.openConnection();
        } else {
            urlConnection = (HttpURLConnection) url.openConnection(proxy);
        }
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setReadTimeout(libratoApiTimeoutInMillis);
        urlConnection.setRequestProperty("content-type", "application/json; charset=utf-8");
        urlConnection.setRequestProperty("Authorization", "Basic " + basicAuthentication);
        urlConnection.setRequestProperty("User-Agent", httpUserAgent);

        serialize(counters, gauges, urlConnection.getOutputStream());
        int responseCode = urlConnection.getResponseCode();
        if (responseCode != 200) {
            exceptionCounter.incrementAndGet();
            logger.warn("Failure {}:'{}' to send result to Librato server '{}' with proxy {}, user {}",
                    responseCode, urlConnection.getResponseMessage(), url, proxy, user);
        }
        if (logger.isTraceEnabled()) {
            IoUtils2.copy(urlConnection.getInputStream(), System.out);
        }
    } catch (Exception e) {
        exceptionCounter.incrementAndGet();
        logger.warn("Failure to send result to Librato server '{}' with proxy {}, user {}", url, proxy, user,
                e);
    } finally {
        if (urlConnection != null) {
            try {
                InputStream in = urlConnection.getInputStream();
                IoUtils2.copy(in, IoUtils2.nullOutputStream());
                IoUtils2.closeQuietly(in);
                InputStream err = urlConnection.getErrorStream();
                if (err != null) {
                    IoUtils2.copy(err, IoUtils2.nullOutputStream());
                    IoUtils2.closeQuietly(err);
                }
            } catch (IOException e) {
                logger.warn("Exception flushing http connection", e);
            }
        }

    }
}

From source file:com.skelril.ShivtrAuth.AuthenticationCore.java

public synchronized JSONArray getFrom(String subAddress) {

    JSONArray objective = new JSONArray();
    HttpURLConnection connection = null;
    BufferedReader reader = null;

    try {// ww  w .jav a2 s.  co m
        JSONParser parser = new JSONParser();
        for (int i = 1; true; i++) {

            try {
                // Establish the connection
                URL url = new URL(websiteURL + subAddress + "?page=" + i);
                connection = (HttpURLConnection) url.openConnection();
                connection.setConnectTimeout(1500);
                connection.setReadTimeout(1500);

                // Check response codes return if invalid
                if (connection.getResponseCode() < 200 || connection.getResponseCode() >= 300)
                    return null;

                // Begin to read results
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder builder = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }

                // Parse Data
                JSONObject o = (JSONObject) parser.parse(builder.toString());
                JSONArray ao = (JSONArray) o.get("characters");
                if (ao.isEmpty())
                    break;
                Collections.addAll(objective, (JSONObject[]) ao.toArray(new JSONObject[ao.size()]));
            } catch (ParseException e) {
                break;
            } finally {
                if (connection != null)
                    connection.disconnect();

                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException ignored) {
                    }
                }
            }
        }
    } catch (IOException e) {
        return null;
    }

    return objective;
}

From source file:com.conx.logistics.kernel.bpm.impl.jbpm.core.mock.BPMGuvnorUtil.java

public boolean canBuildPackage(String packageName) {
    try {//from  www.j a v a2  s.c  o m
        String packagesBinaryURL = getGuvnorProtocol() + "://" + getGuvnorHost() + "/" + getGuvnorSubdomain()
                + "/rest/packages/" + packageName + "/binary";

        URL checkURL = new URL(packagesBinaryURL);
        HttpURLConnection checkConnection = (HttpURLConnection) checkURL.openConnection();
        checkConnection.setRequestMethod("GET");
        checkConnection.setConnectTimeout(Integer.parseInt(getGuvnorConnectTimeout()));
        checkConnection.setReadTimeout(Integer.parseInt(getGuvnorReadTimeout()));
        applyAuth(checkConnection);
        checkConnection.connect();
        return checkConnection.getResponseCode() == 200;
    } catch (Exception e) {
        return false;
    }
}

From source file:com.twotoasters.android.hoot.HootTransportHttpUrlConnection.java

@Override
public HootResult synchronousExecute(HootRequest request) {
    if (request.isCancelled()) {
        return request.getResult();
    }//from   w  w w.ja v a2s  . c  om

    mStreamingMode = (request.getQueryParameters() == null && request.getData() == null
            && request.getMultipartEntity() == null) ? StreamingMode.CHUNKED : StreamingMode.FIXED;

    if (request.getStreamingMode() == HootRequest.STREAMING_MODE_FIXED) {
        mStreamingMode = StreamingMode.FIXED;
    }

    HttpURLConnection connection = null;
    try {
        String url = request.buildUri().toString();
        Log.v(TAG, "Executing [" + url + "]");
        connection = (HttpURLConnection) new URL(url).openConnection();
        if (connection instanceof HttpsURLConnection) {
            HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
            httpsConnection.setHostnameVerifier(mSSLHostNameVerifier);
        }
        connection.setConnectTimeout(mTimeout);
        connection.setReadTimeout(mTimeout);
        synchronized (mConnectionMap) {
            mConnectionMap.put(request, connection);
        }

        setRequestMethod(request, connection);
        setRequestHeaders(request, connection);

        if (request.getMultipartEntity() != null) {
            setMultipartEntity(request, connection);
        } else if (request.getData() != null) {
            setRequestData(request, connection);
        }

        HootResult hootResult = request.getResult();
        hootResult.setResponseCode(connection.getResponseCode());
        Log.d(TAG, " - received response code [" + connection.getResponseCode() + "]");
        if (request.getResult().isSuccess()) {
            hootResult.setHeaders(connection.getHeaderFields());
            hootResult.setResponseStream(new BufferedInputStream(connection.getInputStream()));
        } else {
            hootResult.setResponseStream(new BufferedInputStream(connection.getErrorStream()));
        }
        request.deserializeResult();
    } catch (Exception e) {
        request.getResult().setException(e);
        e.printStackTrace();
    } finally {
        if (connection != null) {
            synchronized (mConnectionMap) {
                mConnectionMap.remove(request);
            }
            connection.disconnect();
            connection = null;
        }
    }
    return request.getResult();
}

From source file:net.kervala.comicsreader.BrowseRemoteAlbumsTask.java

@Override
protected String doInBackground(String... params) {
    String error = null;/*  w w  w. ja  va 2 s. c om*/

    URL url = null;

    try {
        // open a stream on URL
        url = new URL(mUrl);
    } catch (MalformedURLException e) {
        error = e.toString();
        e.printStackTrace();
    }

    boolean retry = false;
    HttpURLConnection urlConnection = null;
    int resCode = 0;

    do {
        // create the new connection
        ComicsAuthenticator.sInstance.reset();

        if (urlConnection != null) {
            urlConnection.disconnect();
        }

        try {
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setConnectTimeout(ComicsParameters.TIME_OUT);
            urlConnection.setReadTimeout(ComicsParameters.TIME_OUT);
            resCode = urlConnection.getResponseCode();
        } catch (EOFException e) {
            // under Android 4
            resCode = -1;
        } catch (IOException e) {
            e.printStackTrace();
        }

        Log.d("ComicsReader", "Rescode " + resCode);

        if (resCode < 0) {
            retry = true;
        } else if (resCode == 401) {
            ComicsAuthenticator.sInstance.setResult(false);

            // user pressed cancel
            if (!ComicsAuthenticator.sInstance.isValidated()) {
                return null;
            }

            retry = true;
        } else {
            retry = false;
        }
    } while (retry);

    if (resCode != HttpURLConnection.HTTP_OK) {
        ComicsAuthenticator.sInstance.setResult(false);

        // TODO: HTTP error occurred 
        return null;
    }

    final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    InputStream is = null;

    try {
        // download the file
        is = new BufferedInputStream(urlConnection.getInputStream(), ComicsParameters.BUFFER_SIZE);

        int count = 0;
        byte data[] = new byte[ComicsParameters.BUFFER_SIZE];

        while ((count = is.read(data)) != -1) {
            bytes.write(data, 0, count);
        }

        ComicsAuthenticator.sInstance.setResult(true);
    } catch (IOException e) {
        error = e.toString();
        e.printStackTrace();
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }

    if (bytes != null) {
        final String text = new String(bytes.toByteArray());

        if (text.contains("<albums>")) {
            parseXml(text);
        } else if (text.contains("\"albums\":")) {
            parseJson(text);
        } else {
            Log.e("ComicsReader", "Error");
        }
    }

    return error;
}

From source file:AIR.Common.Web.HttpWebHelper.java

public String submitForm1(String url, Map<String, Object> formParameters, int maxTries,
        _Ref<Integer> httpStatusCode) throws IOException {
    // 1 Create the Apache Commons PostMethod object.
    // 2 Add everything from formParameters to the PostMethod object as
    // parameters. Remember to run .toString on each object.
    // 3 Make POST calls as show in here:
    // http://hc.apache.org/httpclient-3.x/tutorial.html
    // 4 One divergence from example code in step 3 is that the whole block
    // needs to go into a for loop that will loop over maxTries time until
    // successful or maxTries reached.
    // 5 If any exception happens then wrap that exception in an IOException.
    // 6 Set httpStatusCode to statusCode from the example.

    byte[] encodeDataInBytes = null;

    StringBuilder strn = new StringBuilder();
    StringBuilder payloadBuilder = new StringBuilder();
    for (Map.Entry<String, Object> entry : formParameters.entrySet()) {
        payloadBuilder.append(UrlEncoderDecoderUtils.encode(entry.getKey()) + "="
                + UrlEncoderDecoderUtils.encode(entry.getValue().toString()) + "&");
        strn.append(entry.getKey() + "=" + entry.getValue().toString() + "\n");
    }/*www .  j  a  v  a 2s .  co  m*/
    String encodedData = payloadBuilder.toString();
    // _logger.info ("Python request URL: " + url + " ; request data: " +
    // encodedData);
    encodeDataInBytes = encodedData.getBytes();

    for (int i = 1; i <= maxTries; i++) {
        HttpURLConnection connection = null;

        OutputStream os = null;
        BufferedReader rd = null;
        try {
            connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setConnectTimeout(getTimeoutInMillis());
            connection.setReadTimeout(getTimeoutInMillis());
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Length", "" + encodeDataInBytes.length);
            // connection.setRequestProperty ("Connection", "Close");
            //connection.setRequestProperty ("expect", "100-continue");
            connection.setUseCaches(false);

            os = connection.getOutputStream();
            os.write(encodeDataInBytes);

            httpStatusCode.set(connection.getResponseCode());

            // try reading the result from the server. if there is an error we will
            // automatically go to the exception handler
            rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));

            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = rd.readLine()) != null)
                sb.append(line + "\n");

            return sb.toString();
        } catch (Exception e) {

            _logger.error("Error Url : " + url + " ; post data: " + encodedData);
            _logger.error("================Start Raw==============\n");
            _logger.error(strn.toString());
            _logger.error("================End Raw==============\n");
            _logger.error("Could not retrieve response: ", e.getMessage());
            _logger.error("Stacktrace : " + TDSStringUtils.exceptionToString(e));
            if (i == maxTries)
                throw new IOException(e);
        } finally {
            // close the output stream
            try {
                if (os != null)
                    os.close();
            } catch (Exception e) {
                _logger.error("Error closing socket output stream: ", e.getMessage());
                _logger.error("Stacktrace : " + TDSStringUtils.exceptionToString(e));
                e.printStackTrace();
            }

            // close the input stream
            try {
                if (rd != null)
                    rd.close();
            } catch (Exception e) {
                _logger.error("Error closing socket input stream: ", e.getMessage());
                _logger.error("Stacktrace : " + TDSStringUtils.exceptionToString(e));
                e.printStackTrace();
            }

            try {
                if (connection != null) {
                    // read the errorStream if any and close it.
                    InputStream es = ((HttpURLConnection) connection).getErrorStream();
                    if (es != null) {
                        try {
                            BufferedReader esBfr = new BufferedReader(new InputStreamReader(es));
                            String line = null;
                            // read the response body
                            while ((line = esBfr.readLine()) != null) {
                            }
                        } catch (Exception exp) {
                            _logger.error("Stacktrace : " + TDSStringUtils.exceptionToString(exp));
                        }
                        es.close();
                    }
                }
            } catch (Exception e) {
                _logger.error("Printing error stream: ", e.getMessage());
                _logger.error("Stacktrace : " + TDSStringUtils.exceptionToString(e));
                e.printStackTrace();
            }
            /*
             * try { if (connection != null) { connection.disconnect (); } } catch
             * (Exception e) { _logger.error ("Disconnecting socket: ", e.getMessage
             * ()); _logger.error ("Stacktrace : " +
             * TDSStringUtils.exceptionToString (e)); e.printStackTrace (); }
             */
        }
    }

    // for some reason we ended here. just throw an exception.
    throw new IOException("Could not retrive result.");
}

From source file:de.escidoc.core.test.sb.HttpRequester.java

/**
 * Sends request with given method and given body to given URI and returns result as String.
 *
 * @param resource String resource//from w w  w  . j av a2  s  .c  o m
 * @param method   String method
 * @param body     String body
 * @return String response
 * @throws Exception e
 */
private String requestNoSsl(final String resource, final String method, final String body) throws Exception {
    URL url;
    InputStream is = null;
    StringBuffer response = new StringBuffer();

    // Open Connection to given resource
    url = new URL(domain + resource);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();

    // Set Basic-Authentication Header
    if (securityHandle != null && !securityHandle.equals("")) {
        String encoding = new String(Base64.encodeBase64(securityHandle.getBytes(ClientBase.DEFAULT_CHARSET)));
        con.setRequestProperty("Authorization", "Basic " + encoding);
    }

    // Set request-method and timeout
    con.setRequestMethod(method.toUpperCase(Locale.ENGLISH));
    con.setReadTimeout(TIMEOUT);

    // If PUT or POST, write given body in Output-Stream
    if ((method.equalsIgnoreCase("PUT") || method.equalsIgnoreCase("POST")) && body != null) {
        con.setDoOutput(true);
        OutputStream out = con.getOutputStream();
        out.write(body.getBytes(ClientBase.DEFAULT_CHARSET));
        out.flush();
        out.close();
    }

    // Request
    is = con.getInputStream();

    // Read response
    String currentLine = null;
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    while ((currentLine = br.readLine()) != null) {
        response.append(currentLine + "\n");
    }
    is.close();
    return response.toString();
}

From source file:com.dell.asm.asmcore.asmmanager.util.discovery.DeviceTypeCheckUtil.java

/**
 * HTTP POST with basic auth//from w  ww  . j a  v  a  2 s  .c  o m
 *
 * @param urlToRead device URL
 * @return http response message
 * @throws IOException
 */
public static String httpPost(String urlToRead, String username, String password) throws IOException {
    URL url;
    HttpURLConnection conn;
    BufferedReader rd = null;
    String line;
    StringBuffer result = new StringBuffer();

    try {
        url = new URL(urlToRead);
        conn = (HttpURLConnection) url.openConnection();
        if (conn instanceof HttpsURLConnection) {
            HttpsURLConnection sslConn = (HttpsURLConnection) conn;
            sslConn.setHostnameVerifier(hv);
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, new TrustManager[] { tmNoCheck }, new SecureRandom());
            sslConn.setSSLSocketFactory(sslContext.getSocketFactory());
        }
        conn.setDoOutput(true);
        conn.setConnectTimeout(AsmManagerApp.CONNECT_TIMEOUT); // timeout value
        conn.setReadTimeout(AsmManagerApp.CONNECT_TIMEOUT);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("x-dell-api-version", "2.0");
        conn.setRequestProperty("Authorization", encodeCredentials(username, password));
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setFixedLengthStreamingMode("{}".length());
        conn.getOutputStream().write("{}".getBytes(Charset.forName("UTF-8")));

        rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
    } catch (RuntimeException e) {
        throw new IOException("Could not connect to the url: " + e.getMessage());
    } catch (Exception e) {
        throw new IOException("Could not connect to the url: " + urlToRead);
    } finally {
        if (rd != null)
            rd.close();
    }
    return result.toString();
}