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:edu.usf.cutr.opentripplanner.android.tasks.BikeRentalLoad.java

protected BikeRentalStationList doInBackground(String... reqs) {
    String prefix = PreferenceManager.getDefaultSharedPreferences(context)
            .getString(OTPApp.PREFERENCE_KEY_FOLDER_STRUCTURE_PREFIX, OTPApp.FOLDER_STRUCTURE_PREFIX_NEW);
    String u = reqs[0] + prefix + OTPApp.BIKE_RENTAL_LOCATION;
    Log.d(OTPApp.TAG, "URL: " + u);

    HttpURLConnection urlConnection = null;
    BikeRentalStationList bikeRentalStationList = null;

    try {//from w w w.  j a  v  a 2 s.com
        URL url = new URL(u);
        if (mapper == null) {
            mapper = new ObjectMapper();
        }
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestProperty("Accept", "application/json");
        urlConnection.setConnectTimeout(OTPApp.HTTP_CONNECTION_TIMEOUT);
        urlConnection.setReadTimeout(OTPApp.HTTP_SOCKET_TIMEOUT);
        bikeRentalStationList = mapper.readValue(urlConnection.getInputStream(), BikeRentalStationList.class);
    } catch (IOException e) {
        Log.e(OTPApp.TAG, "Error fetching JSON or XML: " + e);
        e.printStackTrace();
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
    return bikeRentalStationList;
}

From source file:de.schildbach.wallet.ui.send.RequestWalletBalanceTask.java

public void requestWalletBalance(final Address... addresses) {
    backgroundHandler.post(new Runnable() {
        @Override//from w  ww .  ja v  a 2  s .  c  om
        public void run() {
            final StringBuilder url = new StringBuilder(Constants.BITEASY_API_URL);
            url.append("unspent-outputs");
            url.append("?per_page=MAX");
            for (final Address address : addresses)
                url.append("&address[]=").append(address.toString());

            log.debug("trying to request wallet balance from {}", url);

            HttpURLConnection connection = null;
            Reader reader = null;

            try {
                connection = (HttpURLConnection) new URL(url.toString()).openConnection();

                connection.setInstanceFollowRedirects(false);
                connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
                connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
                connection.setUseCaches(false);
                connection.setDoInput(true);
                connection.setDoOutput(false);

                connection.setRequestMethod("GET");
                if (userAgent != null)
                    connection.addRequestProperty("User-Agent", userAgent);
                connection.connect();

                final int responseCode = connection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024),
                            Charsets.UTF_8);
                    final StringBuilder content = new StringBuilder();
                    Io.copy(reader, content);

                    final JSONObject json = new JSONObject(content.toString());

                    final int status = json.getInt("status");
                    if (status != 200)
                        throw new IOException("api status " + status + " when fetching unspent outputs");

                    final JSONObject jsonData = json.getJSONObject("data");

                    final JSONObject jsonPagination = jsonData.getJSONObject("pagination");

                    if (!"false".equals(jsonPagination.getString("next_page")))
                        throw new IllegalStateException("result set too big");

                    final JSONArray jsonOutputs = jsonData.getJSONArray("outputs");

                    final Map<Sha256Hash, Transaction> transactions = new HashMap<Sha256Hash, Transaction>(
                            jsonOutputs.length());

                    for (int i = 0; i < jsonOutputs.length(); i++) {
                        final JSONObject jsonOutput = jsonOutputs.getJSONObject(i);

                        if (jsonOutput.getInt("is_spent") != 0)
                            throw new IllegalStateException("UXTO not spent");

                        final Sha256Hash uxtoHash = new Sha256Hash(jsonOutput.getString("transaction_hash"));
                        final int uxtoIndex = jsonOutput.getInt("transaction_index");
                        final byte[] uxtoScriptBytes = HEX.decode(jsonOutput.getString("script_pub_key"));
                        final Coin uxtoValue = Coin.valueOf(Long.parseLong(jsonOutput.getString("value")));

                        Transaction tx = transactions.get(uxtoHash);
                        if (tx == null) {
                            tx = new FakeTransaction(Constants.NETWORK_PARAMETERS, uxtoHash);
                            tx.getConfidence().setConfidenceType(ConfidenceType.BUILDING);
                            transactions.put(uxtoHash, tx);
                        }

                        if (tx.getOutputs().size() > uxtoIndex)
                            throw new IllegalStateException("cannot reach index " + uxtoIndex
                                    + ", tx already has " + tx.getOutputs().size() + " outputs");

                        // fill with dummies
                        while (tx.getOutputs().size() < uxtoIndex)
                            tx.addOutput(new TransactionOutput(Constants.NETWORK_PARAMETERS, tx,
                                    Coin.NEGATIVE_SATOSHI, new byte[] {}));

                        // add the real output
                        final TransactionOutput output = new TransactionOutput(Constants.NETWORK_PARAMETERS, tx,
                                uxtoValue, uxtoScriptBytes);
                        tx.addOutput(output);
                    }

                    log.info("fetched unspent outputs from {}", url);

                    onResult(transactions.values());
                } else {
                    final String responseMessage = connection.getResponseMessage();

                    log.info("got http error '{}: {}' from {}", responseCode, responseMessage, url);

                    onFail(R.string.error_http, responseCode, responseMessage);
                }
            } catch (final JSONException x) {
                log.info("problem parsing json from " + url, x);

                onFail(R.string.error_parse, x.getMessage());
            } catch (final IOException x) {
                log.info("problem querying unspent outputs from " + url, x);

                onFail(R.string.error_io, x.getMessage());
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final IOException x) {
                        // swallow
                    }
                }

                if (connection != null)
                    connection.disconnect();
            }
        }
    });
}

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

private String httpGET(URL base, String key) {

    InputStream is = null;//w  w  w .  j  a  v a 2s .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;
}

From source file:net.evecom.android.log.DailyLogAddActivity.java

/**
 * connServerForResultPost/* w ww  .  ja  v a 2  s  . c o  m*/
 * 
 * @param strUrl
 * @return
 * @throws IOException
 * @throws ClientProtocolException
 */
private String connServerForResultPost(String strUrl, String entity_str)
        throws ClientProtocolException, IOException {
    String strResult = "";
    URL url = new URL(strUrl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    byte[] entity = entity_str.getBytes();
    conn.setConnectTimeout(5000);
    conn.setDoOutput(true);
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Content-Length", String.valueOf(entity.length));
    conn.getOutputStream().write(entity);
    if (conn.getResponseCode() == 200) {
        InputStream inputstream = conn.getInputStream();
        StringBuffer buffer = new StringBuffer();
        byte[] b = new byte[4096];
        for (int n; (n = inputstream.read(b)) != -1;) {
            buffer.append(new String(b, 0, n));
        }
        strResult = buffer.toString();

    }
    return strResult;
}

From source file:org.hupo.psi.mi.psicquic.registry.PsicquicRegistryStatusChecker.java

private void checkStatus(ServiceType serviceStatus) {
    HttpURLConnection urlConnection = null;
    InputStream contentStream = null;
    InputStream countStream = null;
    try {/*  ww w . j a v a 2  s.c o  m*/

        final URL versionUrl = new URL(serviceStatus.getRestUrl() + "version");
        final URL countURL = new URL(serviceStatus.getRestUrl() + "query/*?format=count");

        urlConnection = (HttpURLConnection) versionUrl.openConnection();
        urlConnection.setConnectTimeout(threadTimeOut * 1000);
        urlConnection.setReadTimeout(threadTimeOut * 1000);

        urlConnection.connect();

        int code = urlConnection.getResponseCode();

        if (HttpURLConnection.HTTP_OK == code) {

            serviceStatus.setActive(true);

            final String version;
            final String strCount;

            //TODO Add a double check to know if the service is active
            // or not add a catch block for the exceptions

            contentStream = (InputStream) urlConnection.getContent();
            version = IOUtils.toString(contentStream);
            serviceStatus.setVersion(version);

            countStream = (InputStream) countURL.getContent();
            strCount = IOUtils.toString(countStream);
            serviceStatus.setCount(Long.valueOf(strCount));
        } else {
            serviceStatus.setActive(false);
        }

    } catch (Throwable e) {
        serviceStatus.setActive(false);
    } finally {
        if (contentStream != null) {
            try {
                contentStream.close();
            } catch (IOException e) {
                log.error("Cannot close psicquic content stream", e);
            }
        }
        if (countStream != null) {
            try {
                countStream.close();
            } catch (IOException e) {
                log.error("Cannot close psicquic count stream", e);
            }
        }
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

From source file:com.google.samples.quickstart.signin.MainActivity.java

private String downloadUrl(String myurl, String tokenid) throws IOException {
    InputStream is = null;//from w ww . j a  va 2s . co  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(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Accept", "application/json");

        JSONObject cred = new JSONObject();
        cred.put("tokenid", tokenid);

        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(cred.toString());
        wr.flush();
        //con.setRequestMethod("POST");
        //conn.setRequestProperty("tokenid",tokenid);
        // Starts the query
        conn.connect();
        int response = conn.getResponseCode();
        Log.d(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.
    } catch (JSONException e) {
        e.printStackTrace();
        return null;
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:com.paymaya.sdk.android.common.network.AndroidClient.java

private HttpURLConnection initializeConnection(Request request) {
    try {//from  w  ww.j  a  v  a2s.  com
        HttpURLConnection conn = (HttpURLConnection) request.getUrl().openConnection();
        if (conn instanceof HttpsURLConnection) {
            try {
                SSLHelper.injectSSLSocketFactory((HttpsURLConnection) conn, SSLHelper.PROTOCOL_TLS_V_1_2);
            } catch (NoSuchAlgorithmException | KeyManagementException ignored) {
                Log.w(TAG, "TLS V1.2 is not supported.");
            }
        }
        conn.setReadTimeout(READ_TIMEOUT);
        conn.setConnectTimeout(CONNECTION_TIMEOUT);
        conn.setRequestProperty(CONTENT_TYPE, CONTENT_TYPE_JSON);
        if (request.getHeaders() != null) {
            for (Map.Entry<String, String> entry : request.getHeaders().entrySet()) {
                conn.setRequestProperty(entry.getKey(), entry.getValue());
            }
        }
        return conn;
    } catch (IOException e) {
        Log.e(TAG, e.getMessage());
        throw new RuntimeException("Invalid URL: " + request.getUrl());
    }
}

From source file:com.chainsaw.clearweather.BackgroundFetch.java

@Override
protected WeatherData doInBackground(String... params) {
    publishProgress(10);//from www.  jav  a2  s  . c  o m

    HttpURLConnection con = null;
    InputStream is = null;

    if (!isNetworkAvailable()) {
        fetchStatus = NO_NETWORK;
    }

    if (isNetworkAvailable()) {

        try {
            con = (HttpURLConnection) (new URL(params[0])).openConnection();
            con.setRequestMethod("GET");
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setConnectTimeout(SERVER_TIMEOUT);
            con.connect();
            buffer = new StringBuffer();
            is = con.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String line = null;
            while ((line = br.readLine()) != null)
                buffer.append(line);
            is.close();
            con.disconnect();
        } catch (Throwable t) {
            fetchStatus = SERVER_ERROR;
            t.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (Throwable t) {
                fetchStatus = SERVER_ERROR;
                t.printStackTrace();
            }
            try {
                con.disconnect();
            } catch (Throwable t) {
                fetchStatus = SERVER_ERROR;
                t.printStackTrace();
            }
        }

        try {
            weatherData = (buffer.toString() == null) ? new JSONObject() : new JSONObject(buffer.toString());
            fetchStatus = DONE;
        } catch (Throwable e) {
            fetchStatus = NO_DATA;
            e.printStackTrace();
        }

        is = null;
        con = null;

        try {
            if ((fetchStatus == DONE) && (weatherData != null)) {
                WeatherData.newDataStatus = DONE;
                JSONObject mainObj = weatherData.getJSONObject("main");
                JSONArray weatherObj = weatherData.getJSONArray("weather");
                returnData = new WeatherData(true, (int) (Math.round(mainObj.getDouble("temp") - 273.15)),
                        ((int) (Math.round(mainObj.getInt("humidity")))), weatherData.getString("name"),
                        ((JSONObject) weatherObj.get(0)).getString("description"));
            }
        } catch (Throwable e) {
            fetchStatus = NO_DATA;
            e.printStackTrace();
        }
    }
    switch (fetchStatus) {
    case NO_DATA:
        WeatherData.newDataStatus = NO_DATA;
        break;
    case SERVER_ERROR:
        WeatherData.newDataStatus = SERVER_ERROR;
        break;
    case NO_NETWORK:
        WeatherData.newDataStatus = NO_NETWORK;
        break;
    }
    if (returnData == null)
        WeatherData.newDataStatus = NO_DATA;

    return returnData;

}

From source file:count.ly.messaging.ConnectionProcessor.java

URLConnection urlConnectionForEventData(final String eventData) throws IOException {
    String urlStr = serverURL_ + "/i?";
    if (!eventData.contains("&crash="))
        urlStr += eventData;/*from  www .  j av a2  s .c  o m*/
    final URL url = new URL(urlStr);
    final HttpURLConnection conn;
    if (Countly.publicKeyPinCertificates == null) {
        conn = (HttpURLConnection) url.openConnection();
    } else {
        HttpsURLConnection c = (HttpsURLConnection) url.openConnection();
        c.setSSLSocketFactory(sslContext_.getSocketFactory());
        conn = c;
    }
    conn.setConnectTimeout(CONNECT_TIMEOUT_IN_MILLISECONDS);
    conn.setReadTimeout(READ_TIMEOUT_IN_MILLISECONDS);
    conn.setUseCaches(false);
    conn.setDoInput(true);
    String picturePath = UserData.getPicturePathFromQuery(url);
    if (Countly.sharedInstance().isLoggingEnabled()) {
        Log.d(Countly.TAG, "Got picturePath: " + picturePath);
    }
    if (!picturePath.equals("")) {
        //Uploading files:
        //http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests

        File binaryFile = new File(picturePath);
        conn.setDoOutput(true);
        // Just generate some unique random value.
        String boundary = Long.toHexString(System.currentTimeMillis());
        // Line separator required by multipart/form-data.
        String CRLF = "\r\n";
        String charset = "UTF-8";
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        OutputStream output = conn.getOutputStream();
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
        // Send binary file.
        writer.append("--" + boundary).append(CRLF);
        writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName()
                + "\"").append(CRLF);
        writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName()))
                .append(CRLF);
        writer.append("Content-Transfer-Encoding: binary").append(CRLF);
        writer.append(CRLF).flush();
        FileInputStream fileInputStream = new FileInputStream(binaryFile);
        byte[] buffer = new byte[1024];
        int len;
        while ((len = fileInputStream.read(buffer)) != -1) {
            output.write(buffer, 0, len);
        }
        output.flush(); // Important before continuing with writer!
        writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.
        fileInputStream.close();

        // End of multipart/form-data.
        writer.append("--" + boundary + "--").append(CRLF).flush();
    } else if (eventData.contains("&crash=")) {
        if (Countly.sharedInstance().isLoggingEnabled()) {
            Log.d(Countly.TAG, "Using post because of crash");
        }
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        writer.write(eventData);
        writer.flush();
        writer.close();
        os.close();
    } else {
        conn.setDoOutput(false);
    }
    return conn;
}

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

public PhotoEntry doResumableUpload(com.google.ytd.model.PhotoEntry photoEntry)
        throws IllegalArgumentException {
    if (util.isNullOrEmpty(photoEntry.getResumableUploadUrl())) {
        throw new IllegalArgumentException(String
                .format("No resumable upload URL found for " + "PhotoEntry id '%s'.", photoEntry.getId()));
    }//from  w  ww.  j  av  a2  s .c  om

    try {
        URL url = new URL(photoEntry.getResumableUploadUrl());

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setInstanceFollowRedirects(false);
        connection.setConnectTimeout(CONNECT_TIMEOUT);
        connection.setReadTimeout(READ_TIMEOUT);
        connection.setRequestMethod("PUT");

        connection.setRequestProperty("Content-Range", "bytes */*");

        // Response code 308 is specific to this use case and doesn't appear to have a
        // HttpURLConnection constant.
        if (connection.getResponseCode() == 308) {
            long previousByte = 0;

            String rangeHeader = connection.getHeaderField("Range");
            if (!util.isNullOrEmpty(rangeHeader)) {
                LOG.info("Range header in 308 response is " + rangeHeader);

                String[] rangeHeaderSplits = rangeHeader.split("-", 2);
                if (rangeHeaderSplits.length == 2) {
                    previousByte = Long.valueOf(rangeHeaderSplits[1]).longValue() + 1;
                }
            }

            connection = (HttpURLConnection) url.openConnection();
            connection.setInstanceFollowRedirects(false);
            connection.setDoOutput(true);
            connection.setConnectTimeout(CONNECT_TIMEOUT);
            connection.setReadTimeout(READ_TIMEOUT);
            connection.setRequestMethod("PUT");

            byte[] bytes;
            String contentRangeHeader;

            if (photoEntry.getBlobKey() != null) {
                long lastByte = previousByte + CHUNK_SIZE;
                if (lastByte > (photoEntry.getOriginalFileSize() - 1)) {
                    lastByte = photoEntry.getOriginalFileSize() - 1;
                }

                contentRangeHeader = String.format("bytes %d-%d/%d", previousByte, lastByte,
                        photoEntry.getOriginalFileSize());

                BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
                bytes = blobstoreService.fetchData(photoEntry.getBlobKey(), previousByte, lastByte);
            } else {
                bytes = dataChunkDao.getBytes(photoEntry.getId(), previousByte);

                if (bytes == null) {
                    throw new IllegalArgumentException(String.format("PhotoEntry with id '%s' does not "
                            + "have a valid blob key. Additionally, there is no DataChunk entry for the "
                            + "initial byte '%d'.", photoEntry.getId(), previousByte));
                }

                contentRangeHeader = String.format("bytes %d-%d/%d", previousByte,
                        previousByte + bytes.length - 1, photoEntry.getOriginalFileSize());
            }

            connection.setRequestProperty("Content-Length", String.valueOf(bytes.length));

            LOG.info("Using the following for Content-Range header: " + contentRangeHeader);
            connection.setRequestProperty("Content-Range", contentRangeHeader);

            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(bytes);
            outputStream.close();

            if (connection.getResponseCode() == HttpURLConnection.HTTP_CREATED) {
                LOG.info("Resumable upload is complete and successful.");

                return (PhotoEntry) ParseUtil.readEntry(new ParseSource(connection.getInputStream()));
            }
        } else if (connection.getResponseCode() == HttpURLConnection.HTTP_CREATED) {
            // It's possible that the Picasa upload associated with the specific resumable upload URL
            // had previously completed successfully. In that case, the response to the initial */* PUT
            // will be a 201 Created with the new PhotoEntry. This is probably an edge case.
            LOG.info("Resumable upload is complete and successful.");

            return (PhotoEntry) ParseUtil.readEntry(new ParseSource(connection.getInputStream()));
        } else {
            // The IllegalArgumentException should be treated by the calling code as
            // something that is not recoverable, which is to say the resumable upload attempt
            // should be stopped.
            throw new IllegalArgumentException(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);
    } catch (ServiceException e) {
        LOG.log(Level.WARNING, "", e);
    }

    return null;
}