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:eu.codeplumbers.cosi.services.CosiSmsService.java

public void sendChangesToCozy() {
    List<Sms> unSyncedSms = Sms.getAllUnsynced();
    int i = 0;// w w w .  j  a va2s  .  c o m
    for (Sms sms : unSyncedSms) {
        URL urlO = null;
        try {
            JSONObject jsonObject = sms.toJsonObject();
            mBuilder.setProgress(unSyncedSms.size(), i, false);
            mBuilder.setContentText("Syncing " + jsonObject.getString("docType") + ":");
            mNotifyManager.notify(notification_id, mBuilder.build());
            EventBus.getDefault()
                    .post(new SmsSyncEvent(SYNC_MESSAGE, getString(R.string.lbl_sms_status_read_phone)));
            String remoteId = jsonObject.getString("remoteId");
            String requestMethod = "";

            if (remoteId.isEmpty()) {
                urlO = new URL(syncUrl);
                requestMethod = "POST";
            } else {
                urlO = new URL(syncUrl + remoteId + "/");
                requestMethod = "PUT";
            }

            HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestProperty("Authorization", authHeader);
            conn.setDoOutput(true);
            conn.setDoInput(true);

            conn.setRequestMethod(requestMethod);

            // set request body
            jsonObject.remove("remoteId");
            long objectId = jsonObject.getLong("id");
            jsonObject.remove("id");
            OutputStream os = conn.getOutputStream();
            os.write(jsonObject.toString().getBytes("UTF-8"));
            os.flush();

            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());

            StringWriter writer = new StringWriter();
            IOUtils.copy(in, writer, "UTF-8");
            String result = writer.toString();

            JSONObject jsonObjectResult = new JSONObject(result);

            if (jsonObjectResult != null && jsonObjectResult.has("_id")) {
                result = jsonObjectResult.getString("_id");
                sms.setRemoteId(result);
                sms.save();
            }

            in.close();
            conn.disconnect();

        } catch (MalformedURLException e) {
            EventBus.getDefault().post(new SmsSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        } catch (ProtocolException e) {
            EventBus.getDefault().post(new SmsSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        } catch (IOException e) {
            EventBus.getDefault().post(new SmsSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        } catch (JSONException e) {
            EventBus.getDefault().post(new SmsSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        }
        i++;
    }
}

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

private String downloadUrl(String myurl) throws IOException {
    InputStream is = null;/*from  www.  j  a  v a 2s  .com*/
    // 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:foam.nanos.geocode.GoogleMapsGeocodingDAO.java

@Override
public FObject put_(X x, FObject obj) {
    final FObject result = super.put_(x, obj);

    ((FixedThreadPool) x.get("threadPool")).submit(x, new ContextAgent() {
        @Override/* w  w w .  j  a  v  a  2s. c o m*/
        public void execute(X x) {
            // don't geocode if no address property
            Address address = (Address) prop_.get(result);
            if (address == null) {
                return;
            }

            // check if address updated
            if (address.getLatitude() != 0 && address.getLongitude() != 0) {
                FObject stored = getDelegate().find(result.getProperty("id"));
                if (stored != null && prop_.get(result) != null) {
                    Address storedAddress = (Address) prop_.get(result);
                    // compare fields that are used to populate Google maps query
                    if (SafetyUtil.compare(address.getAddress(), storedAddress.getAddress()) == 0
                            && SafetyUtil.compare(address.getCity(), storedAddress.getCity()) == 0
                            && SafetyUtil.compare(address.getRegionId(), storedAddress.getRegionId()) == 0
                            && SafetyUtil.compare(address.getPostalCode(), storedAddress.getPostalCode()) == 0
                            && SafetyUtil.compare(address.getCountryId(), storedAddress.getCountryId()) == 0) {
                        return;
                    }
                }
            }

            StringBuilder builder = sb.get().append(API_HOST);
            // append address
            if (!SafetyUtil.isEmpty(address.getAddress())) {
                builder.append(address.getAddress()).append(",");
            }

            // append city
            if (!SafetyUtil.isEmpty(address.getCity())) {
                builder.append(address.getCity()).append(",");
            }

            // append province
            if (!SafetyUtil.isEmpty((String) address.getRegionId())) {
                builder.append((String) address.getRegionId()).append(",");
            }

            // append postal code
            if (!SafetyUtil.isEmpty(address.getPostalCode())) {
                builder.append(address.getPostalCode()).append(",");
            }

            // append country id
            if (!SafetyUtil.isEmpty((String) address.getCountryId())) {
                builder.append((String) address.getCountryId());
            }

            // append api key
            builder.append("&key=").append(apiKey_);

            String line = null;
            HttpURLConnection conn = null;
            BufferedReader reader = null;

            try {
                URL url = new URL(builder.toString().replace(" ", "+"));
                conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(5 * 1000);
                conn.setRequestMethod("GET");
                conn.connect();

                builder.setLength(0);
                reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }

                GoogleMapsGeocodeResponse response = (GoogleMapsGeocodeResponse) getX().create(JSONParser.class)
                        .parseString(builder.toString(), GoogleMapsGeocodeResponse.class);
                if (response == null) {
                    throw new Exception("Invalid response");
                }

                if (!"OK".equals(response.getStatus())) {
                    throw new Exception(
                            !SafetyUtil.isEmpty(response.getError_message()) ? response.getError_message()
                                    : "Invalid response");
                }

                GoogleMapsGeocodeResult[] results = response.getResults();
                if (results == null || results.length == 0) {
                    throw new Exception("Results not found");
                }

                GoogleMapsGeometry geometry = results[0].getGeometry();
                if (geometry == null) {
                    throw new Exception("Unable to determine latitude and longitude");
                }

                GoogleMapsCoordinates coords = geometry.getLocation();
                if (coords == null) {
                    throw new Exception("Unable to determine latitude and longitude");
                }

                // set latitude and longitude
                address.setLatitude(coords.getLat());
                address.setLongitude(coords.getLng());
                prop_.set(result, address);
                GoogleMapsGeocodingDAO.super.put_(x, result);
            } catch (Throwable ignored) {
            } finally {
                IOUtils.closeQuietly(reader);
                IOUtils.close(conn);
            }
        }
    });

    return result;
}

From source file:com.galileha.smarthome.SmartHome.java

/**
 * Read home.json from Server/*from   ww  w . j  ava  2s  . co  m*/
 * 
 * @param URL
 * @return
 * @throws IOException
 *             , MalformedURLException, JSONException
 */
public void getHomeStatus() throws IOException, MalformedURLException, JSONException {
    // Set URL
    // Connect to Intel Galileo get Device Status
    HttpURLConnection httpCon = (HttpURLConnection) homeJSONUrl.openConnection();
    httpCon.setReadTimeout(10000);
    httpCon.setConnectTimeout(15000);
    httpCon.setRequestMethod("GET");
    httpCon.setDoInput(true);
    httpCon.connect();
    // Read JSON File as InputStream
    InputStream readStream = httpCon.getInputStream();
    Scanner scan = new Scanner(readStream).useDelimiter("\\A");
    // Set stream to String
    String jsonFile = scan.hasNext() ? scan.next() : "";
    // Initialize serveFile as read string
    homeInfo = new JSONObject(jsonFile);
    httpCon.disconnect();
}

From source file:eu.codeplumbers.cosi.services.CosiSmsService.java

private List<Sms> getRemoteMessages() {
    allSms.clear();//from ww  w  .j a va 2s  .  c o  m
    URL urlO = null;
    try {
        urlO = new URL(designUrl);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONArray jsonArray = new JSONArray(result);

        if (jsonArray != null) {
            if (jsonArray.length() == 0) {
                EventBus.getDefault()
                        .post(new SmsSyncEvent(SYNC_MESSAGE, "Your Cozy has no Text messages stored."));
                Sms.setAllUnsynced();
            } else {
                for (int i = 0; i < jsonArray.length(); i++) {
                    mBuilder.setProgress(jsonArray.length(), i, false);
                    mNotifyManager.notify(notification_id, mBuilder.build());
                    EventBus.getDefault()
                            .post(new SmsSyncEvent(SYNC_MESSAGE, getString(R.string.lbl_sms_status_read_cozy)));

                    JSONObject smsJson = jsonArray.getJSONObject(i).getJSONObject("value");
                    Sms sms = Sms.getBySystemIdAddressAndBody(smsJson.get("systemId").toString(),
                            smsJson.getString("address"), smsJson.getString("body"));
                    if (sms == null) {
                        sms = new Sms(smsJson);
                    } else {
                        sms.setRemoteId(smsJson.getString("_id"));
                        sms.setSystemId(smsJson.getString("systemId"));
                        sms.setAddress(smsJson.getString("address"));
                        sms.setBody(smsJson.getString("body"));

                        if (smsJson.has("readState")) {
                            sms.setReadState(smsJson.getBoolean("readState"));
                        }

                        sms.setDateAndTime(smsJson.getString("dateAndTime"));
                        sms.setType(smsJson.getInt("type"));
                    }

                    sms.save();

                    allSms.add(sms);
                }
            }
        } else {
            errorMessage = "Failed to parse API response";
            EventBus.getDefault().post(new SmsSyncEvent(SERVICE_ERROR, "Failed to parse API response"));
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        e.printStackTrace();
        errorMessage = e.getLocalizedMessage();
    } catch (ProtocolException e) {
        errorMessage = e.getLocalizedMessage();
        e.printStackTrace();
    } catch (IOException e) {
        errorMessage = e.getLocalizedMessage();
        e.printStackTrace();
    } catch (JSONException e) {
        errorMessage = e.getLocalizedMessage();
        e.printStackTrace();
    }
    return allSms;
}

From source file:com.yahoo.druid.hadoop.DruidInputFormat.java

private String getSegmentsToLoad(String dataSource, Interval interval, String overlordUrl) {
    String urlStr = "http://" + overlordUrl + "/druid/indexer/v1/action";
    logger.info("Sending request to overlord at " + urlStr);

    String requestJson = getSegmentListUsedActionJson(dataSource, interval.toString());
    logger.info("request json is " + requestJson);

    int numTries = 3;
    for (int trial = 0; trial < numTries; trial++) {
        try {/*from w  ww.  j  ava  2 s  .  c om*/
            logger.info("attempt number {} to get list of segments from overlord", trial);
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("content-type", "application/json");
            conn.setRequestProperty("Accept", "*/*");
            conn.setUseCaches(false);
            conn.setDoOutput(true);
            conn.setConnectTimeout(60000);
            OutputStream out = conn.getOutputStream();
            out.write(requestJson.getBytes());
            out.close();
            int responseCode = conn.getResponseCode();
            if (responseCode == 200) {
                return IOUtils.toString(conn.getInputStream());
            } else {
                logger.warn(
                        "Attempt Failed to get list of segments from overlord. response code [%s] , response [%s]",
                        responseCode, IOUtils.toString(conn.getInputStream()));
            }
        } catch (Exception ex) {
            logger.warn("Exception in getting list of segments from overlord", ex);
        }

        try {
            Thread.sleep(5000); //wait before next trial
        } catch (InterruptedException ex) {
            Throwables.propagate(ex);
        }
    }

    throw new RuntimeException(
            String.format("failed to find list of segments, dataSource[%s], interval[%s], overlord[%s]",
                    dataSource, interval, overlordUrl));
}

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

private String downloadContent(String myurl) throws IOException {
    InputStream is = null;// ww w.j  a  v a2s .  c  o  m
    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  av a2 s .  c o  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:com.hp.hpl.jena.sparql.engine.http.HttpQuery.java

private void applyTimeouts(HttpURLConnection conn) {
    if (connectTimeout > 0) {
        conn.setConnectTimeout(connectTimeout);
    }// www.  ja  v  a2s  .c om
    if (readTimeout > 0) {
        conn.setReadTimeout(readTimeout);
    }
}