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:io.apiman.gateway.platforms.servlet.connectors.HttpApiConnection.java

/**
 * If the endpoint properties includes a connect timeout override, then 
 * set it here.//w w  w . j  av a2 s. c  o  m
 * @param connection
 */
private void setConnectTimeout(HttpURLConnection connection) {
    try {
        Map<String, String> endpointProperties = this.api.getEndpointProperties();
        if (endpointProperties.containsKey("timeouts.connect")) { //$NON-NLS-1$
            int connectTimeoutMs = new Integer(endpointProperties.get("timeouts.connect")); //$NON-NLS-1$
            connection.setConnectTimeout(connectTimeoutMs);
        }
    } catch (Throwable t) {
    }
}

From source file:com.ivanbratoev.festpal.datamodel.db.external.ExternalDatabaseHandler.java

/**
 * check whether connection to the database server can be established
 *
 * @return true on success false otherwise
 *///  w  w w .ja  v a2s .co  m
public boolean canConnectToDB() {
    try {
        URL url = new URL(ExternalDatabaseHelper.getAddress());
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(15_000);
        connection.connect();
        connection.disconnect();
        return true;
    } catch (Exception ignore) {
    }
    return false;
}

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

public String getProcessImageURLFromGuvnor(String processId) {
    List<String> allPackages = getPackageNames();
    for (String pkg : allPackages) {
        // query the package to get a list of all processes in this package
        List<String> allProcessesInPackage = getAllProcessesInPackage(pkg);
        // check each process to see if it has the matching id set
        for (String process : allProcessesInPackage) {
            String processContent = getProcessSourceContent(pkg, process);
            Pattern p = Pattern.compile("<\\S*process[\\s\\S]*id=\"" + processId + "\"", Pattern.MULTILINE);
            Matcher m = p.matcher(processContent);
            if (m.find()) {
                try {
                    String imageBinaryURL = getGuvnorProtocol() + "://" + getGuvnorHost() + "/"
                            + getGuvnorSubdomain() + "/org.drools.guvnor.Guvnor/package/" + pkg + "/"
                            + getGuvnorSnapshotName() + "/" + URLEncoder.encode(processId, "UTF-8")
                            + "-image.png";

                    URL checkURL = new URL(imageBinaryURL);
                    HttpURLConnection checkConnection = (HttpURLConnection) checkURL.openConnection();
                    checkConnection.setRequestMethod("GET");
                    checkConnection.setConnectTimeout(Integer.parseInt(getGuvnorConnectTimeout()));
                    checkConnection.setReadTimeout(Integer.parseInt(getGuvnorReadTimeout()));
                    applyAuth(checkConnection);
                    checkConnection.connect();

                    if (checkConnection.getResponseCode() == 200) {
                        return imageBinaryURL;
                    }//from  w w w.  j ava  2s  . c  o  m

                } catch (Exception e) {
                    logger.error("Could not read process image: " + e.getMessage());
                    throw new RuntimeException("Could not read process image: " + e.getMessage());
                }
            }
        }
    }
    logger.info("Did not find process image for: " + processId);
    return null;
}

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

@Override
public HootResult synchronousExecute(HootRequest request) {
    if (request.isCancelled()) {
        return request.getResult();
    }// ww  w  .  j a v  a 2 s. c  o m

    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:org.ednovo.gooru.service.ResourceCassandraServiceImpl.java

public Integer urlStatusChecker(String url) {

    HttpURLConnection connection = null;
    int responseCode;
    try {/*from ww  w .  j  a  v a  2 s .c om*/
        connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("User-Agent", "Mozilla/5.0");
        responseCode = connection.getResponseCode();
        connection.setConnectTimeout(180000);
    } catch (Exception e) {
        if (connection != null) {
            try {
                return connection.getResponseCode();
            } catch (IOException e1) {
                return 404;
            }
        }
        return 404;
    }
    return responseCode;
}

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

/**
 * HTTP POST with basic auth/*from  w  ww  . j  ava  2  s  . co  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();
}

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

/**
 * HTTP request extractor/*w w w .j a v a 2  s.c o  m*/
 *
 * @param urlToRead device URL
 * @return device type string
 * @throws IOException
 */
public static String getHTML(String urlToRead) 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.setRequestMethod("GET");
        conn.setConnectTimeout(AsmManagerApp.CONNECT_TIMEOUT); // timeout value
        conn.setReadTimeout(AsmManagerApp.CONNECT_TIMEOUT);
        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();
}

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");
    }/*from ww w  . j  a va  2  s. c  o 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:net.reichholf.dreamdroid.helpers.SimpleHttpClient.java

/**
 * @param uri//w w  w.j  a va  2 s  .  c  o m
 * @param parameters
 * @return
 */
public boolean fetchPageContent(String uri, List<NameValuePair> parameters) {
    // Set login, ssl, port, host etc;
    applyConfig();

    mErrorText = "";
    mErrorTextId = -1;
    mError = false;
    mBytes = new byte[0];
    if (!uri.startsWith("/")) {
        uri = "/".concat(uri);
    }

    HttpURLConnection conn = null;
    try {
        if (mProfile.getSessionId() != null)
            parameters.add(new BasicNameValuePair("sessionid", mProfile.getSessionId()));
        URL url = new URL(buildUrl(uri, parameters));
        conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(mConnectionTimeoutMillis);
        if (DreamDroid.featurePostRequest())
            conn.setRequestMethod("POST");
        setAuth(conn);
        if (conn.getResponseCode() != 200) {
            if (conn.getResponseCode() == HttpURLConnection.HTTP_BAD_METHOD
                    && mRememberedReturnCode != HttpURLConnection.HTTP_BAD_METHOD) {
                // Method not allowed, the target device either can't handle
                // POST or GET requests (old device or Anti-Hijack enabled)
                DreamDroid.setFeaturePostRequest(!DreamDroid.featurePostRequest());
                conn.disconnect();
                mRememberedReturnCode = HttpURLConnection.HTTP_BAD_METHOD;
                return fetchPageContent(uri, parameters);
            }
            if (conn.getResponseCode() == HttpURLConnection.HTTP_PRECON_FAILED
                    && mRememberedReturnCode != HttpURLConnection.HTTP_PRECON_FAILED) {
                createSession();
                conn.disconnect();
                mRememberedReturnCode = HttpURLConnection.HTTP_PRECON_FAILED;
                return fetchPageContent(uri, parameters);
            }
            mRememberedReturnCode = 0;
            Log.e(LOG_TAG, Integer.toString(conn.getResponseCode()));
            switch (conn.getResponseCode()) {
            case HttpURLConnection.HTTP_UNAUTHORIZED:
                mErrorTextId = R.string.auth_error;
                break;
            default:
                mErrorTextId = -1;
            }
            mErrorText = conn.getResponseMessage();
            mError = true;
            return false;
        }

        BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        int read = 0;
        int bufSize = 512;
        byte[] buffer = new byte[bufSize];
        while ((read = bis.read(buffer)) != -1) {
            baf.append(buffer, 0, read);
        }

        mBytes = baf.toByteArray();
        if (DreamDroid.dumpXml())
            dumpToFile(url);
        return true;

    } catch (MalformedURLException e) {
        mError = true;
        mErrorTextId = R.string.illegal_host;
    } catch (UnknownHostException e) {
        mError = true;
        mErrorText = null;
        mErrorTextId = R.string.host_not_found;
    } catch (ProtocolException e) {
        mError = true;
        mErrorText = e.getLocalizedMessage();
    } catch (ConnectException e) {
        mError = true;
        mErrorTextId = R.string.host_unreach;
    } catch (IOException e) {
        e.printStackTrace();
        mError = true;
        mErrorText = e.getLocalizedMessage();
    } finally {
        if (conn != null)
            conn.disconnect();
        if (mError)
            if (mErrorText == null)
                mErrorText = "Error text is null";
        Log.e(LOG_TAG, mErrorText);
    }

    return false;
}