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:com.embeddedlog.LightUpDroid.LightUpPiSync.java

/**
 * Initiates a background thread to check if the LightUpPi server is reachable.
 *
 * @param guiHandler Handler for the activity GUI, for which to send one of the two runnables.
 * @param online Runnable to execute in the Handler if the server is online.
 * @param offline Runnable to execute in the Handler if the server is offline.
 *///from  w  w  w. java 2  s.  c o m
public void startBackgroundServerCheck(final Handler guiHandler, final Runnable online,
        final Runnable offline) {
    // Check for network connectivity
    ConnectivityManager connMgr = (ConnectivityManager) mActivityContext
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    if ((networkInfo != null) && networkInfo.isConnected()
            && ((scheduleServerCheck == null) || scheduleServerCheck.isShutdown())) {
        // Get the ping address
        final Uri.Builder pingUri = getServerUriBuilder();
        pingUri.appendPath("ping");
        // Schedule the background server check
        scheduleServerCheck = Executors.newScheduledThreadPool(1);
        scheduleServerCheck.scheduleWithFixedDelay(new Runnable() {
            public void run() {
                int response = 0;
                try {
                    URL url = new URL(pingUri.build().toString());
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setReadTimeout(3000); /* milliseconds */
                    conn.setConnectTimeout(5000); /* milliseconds */
                    conn.setRequestMethod("GET");
                    conn.setDoInput(true);
                    conn.connect();
                    response = conn.getResponseCode();
                } catch (Exception e) {
                    // Safely ignored as a response!=200 will trigger the offline title
                }
                if (response == 200) {
                    if (Log.LOGV)
                        Log.i(LOG_TAG + "Server response 200");
                    guiHandler.post(online);
                } else {
                    if (Log.LOGV)
                        Log.i(LOG_TAG + "Server response NOT 200");
                    guiHandler.post(offline);
                }
            }
        }, 0, 30, TimeUnit.SECONDS);
        if (Log.LOGV)
            Log.v(LOG_TAG + "BackgroundServerCheck started");
    } else {
        if (Log.LOGV)
            Log.d(LOG_TAG + "Server response NOT 200");
        guiHandler.post(offline);
    }
}

From source file:com.checkmarx.jenkins.CxWebService.java

private void checkServerConnectivity(URL url) throws AbortException {
    int seconds = CxConfig.getRequestTimeOutDuration();
    int milliseconds = seconds * 1000;

    try {/*from   ww w.j  av a 2s  .c  om*/
        HttpURLConnection urlConn;
        urlConn = (HttpURLConnection) url.openConnection();
        urlConn.setConnectTimeout(milliseconds);
        urlConn.setReadTimeout(milliseconds);
        urlConn.connect();
        if (urlConn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new AbortException(CHECKMARX_SERVER_WAS_NOT_FOUND_ON_THE_SPECIFIED_ADRESS);
        }
    } catch (IOException e) {
        logger.debug(CHECKMARX_SERVER_WAS_NOT_FOUND_ON_THE_SPECIFIED_ADRESS, e);
        throw new AbortException(CHECKMARX_SERVER_WAS_NOT_FOUND_ON_THE_SPECIFIED_ADRESS);
    }
}

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

public String getFormTemplateURLFromGuvnor(String templateName, String format) {
    List<String> allPackages = getPackageNames();
    try {//from   ww w.  j a  v  a 2 s . c om
        for (String pkg : allPackages) {
            String templateURL = getGuvnorProtocol() + "://" + getGuvnorHost() + "/" + getGuvnorSubdomain()
                    + "/rest/packages/" + pkg + "/assets/" + URLEncoder.encode(templateName, "UTF-8");

            URL checkURL = new URL(templateURL);
            HttpURLConnection checkConnection = (HttpURLConnection) checkURL.openConnection();
            checkConnection.setRequestMethod("GET");
            checkConnection.setRequestProperty("Accept", "application/atom+xml");
            checkConnection.setConnectTimeout(Integer.parseInt(getGuvnorConnectTimeout()));
            checkConnection.setReadTimeout(Integer.parseInt(getGuvnorReadTimeout()));
            applyAuth(checkConnection);
            checkConnection.connect();
            if (checkConnection.getResponseCode() == 200) {

                String toReturnURL = getGuvnorProtocol() + "://" + getGuvnorHost() + "/" + getGuvnorSubdomain()
                        + "/org.drools.guvnor.Guvnor/package/" + pkg + "/" + getGuvnorSnapshotName() + "/"
                        + URLEncoder.encode(templateName, "UTF-8") + "." + format;

                return toReturnURL;
            }
        }
    } catch (Exception e) {
        logger.error("Exception returning template url : " + e.getMessage());
        return null;
    }
    logger.info("Could not find process template url for: " + templateName);
    return null;
}

From source file:de.alosdev.android.customerschoice.CustomersChoice.java

private void internalConfigureByNetwork(final Context context, String fileAddress) {
    new AsyncTask<String, Void, Void>() {
        @Override//  w  w  w. j  a va2s  .  c o  m
        protected Void doInBackground(String... args) {
            String value = args[0];
            try {
                final SharedPreferences preferences = getPreferences(context);
                final URL url = new URL(value);
                log.d(TAG, "read from: ", value);

                final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(10000 /* milliseconds */);
                conn.setConnectTimeout(15000 /* milliseconds */);

                // set etag header if existing
                final String fieldEtag = preferences.getString(getPreferencesKey(value, FIELD_ETAG), null);
                if (null != fieldEtag) {
                    conn.setRequestProperty("If-None-Match", fieldEtag);
                }

                // set modified since header if existing
                final long fieldLastModified = preferences
                        .getLong(getPreferencesKey(value, FIELD_LAST_MODIFIED), 0);
                if (fieldLastModified > 0) {
                    conn.setIfModifiedSince(fieldLastModified);
                }
                conn.connect();

                final int response = conn.getResponseCode();

                if (HttpStatus.SC_OK == response) {
                    log.d(TAG, "found file");
                    readFromInputStream(conn.getInputStream());

                    // writing caching information into preferences
                    final Editor editor = preferences.edit();
                    editor.putString(getPreferencesKey(value, FIELD_ETAG), conn.getHeaderField("ETag"));
                    editor.putLong(getPreferencesKey(value, FIELD_LAST_MODIFIED),
                            conn.getHeaderFieldDate("Last-Modified", 0));
                    editor.commit();
                } else if (HttpStatus.SC_NOT_MODIFIED == response) {
                    log.i(TAG, "no updates, file not modified: ", value);
                } else {
                    log.e(TAG, "cannot read from: ", value, " and get following response code:", response);
                }
            } catch (MalformedURLException e) {
                log.e(TAG, e, "the given URL is malformed: ", value);
            } catch (IOException e) {
                log.e(TAG, e, "Error during reading the file: ", value);
            }
            return null;
        }

    }.execute(fileAddress);
}

From source file:com.dawg6.d3api.server.D3IO.java

private <T> T readValue(ObjectMapper mapper, URL url, Class<T> clazz, int retries)
        throws JsonParseException, JsonMappingException, IOException {

    //      log.info("URL " + url);

    HttpURLConnection c = (HttpURLConnection) url.openConnection();
    c.setRequestMethod("GET");
    c.setRequestProperty("Content-length", "0");
    c.setUseCaches(false);// w  w w . j a va2  s .c om
    c.setAllowUserInteraction(false);
    c.setConnectTimeout(connectTimeout);
    c.setReadTimeout(readTimeout);
    c.connect();
    int status = c.getResponseCode();

    switch (status) {
    case 200:
    case 201:
        BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();

        try {
            mapper = mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

            return mapper.readValue(sb.toString(), clazz);
        } catch (Exception e) {
            log.severe("JSON = " + sb.toString());
            log.log(Level.SEVERE, e.getMessage());

            return null;
        }

    case 408:
    case 504:
        log.info("HTTP Response: " + status + ", retries = " + retries + ", URL: " + url);
        errors++;
        onError(status);

        if (retries > 0) {
            retryAttempts++;
            onRetry();
            return readValue(mapper, url, clazz, retries - 1);
        } else
            return null;

    default:
        log.severe("HTTP Response: " + status + ", URL: " + url);
        return null;
    }
}

From source file:org.sogrey.frame.utils.FileUtil.java

/**
 * ????./* w ww  .ja  v  a2 s .  co m*/
 *
 * @param Url
 *         
 *
 * @return int ?
 */
public static int getContentLengthFromUrl(String Url) {
    int mContentLength = 0;
    try {
        URL url = new URL(Url);
        HttpURLConnection mHttpURLConnection = (HttpURLConnection) url.openConnection();
        mHttpURLConnection.setConnectTimeout(5 * 1000);
        mHttpURLConnection.setRequestMethod("GET");
        mHttpURLConnection.setRequestProperty("Accept",
                "image/gif, image/jpeg, image/pjpeg, image/pjpeg, "
                        + "application/x-shockwave-flash, application/xaml+xml, "
                        + "application/vnd.ms-xpsdocument, application/x-ms-xbap, "
                        + "application/x-ms-application, application/vnd.ms-excel, "
                        + "application/vnd.ms-powerpoint, application/msword, */*");
        mHttpURLConnection.setRequestProperty("Accept-Language", "zh-CN");
        mHttpURLConnection.setRequestProperty("Referer", Url);
        mHttpURLConnection.setRequestProperty("Charset", "UTF-8");
        mHttpURLConnection.setRequestProperty("User-Agent",
                "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET"
                        + " CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR"
                        + " 3.0.4506.2152; .NET CLR 3.5.30729)");
        mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive");
        mHttpURLConnection.connect();
        if (mHttpURLConnection.getResponseCode() == 200) {
            // ????
            mContentLength = mHttpURLConnection.getContentLength();
        }
    } catch (Exception e) {
        e.printStackTrace();
        LogUtil.d(FileUtil.class, "?" + e.getMessage());
    }
    return mContentLength;
}

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

public boolean templateExistsInRepo(String templateName) throws Exception {
    List<String> allPackages = getPackageNames();
    try {// w  w  w. j a  va  2s  .c  om
        for (String pkg : allPackages) {
            String templateURL = getGuvnorProtocol() + "://" + getGuvnorHost() + "/" + getGuvnorSubdomain()
                    + "/rest/packages/" + pkg + "/assets/" + URLEncoder.encode(templateName, "UTF-8");

            URL checkURL = new URL(templateURL);
            HttpURLConnection checkConnection = (HttpURLConnection) checkURL.openConnection();
            checkConnection.setRequestMethod("GET");
            checkConnection.setRequestProperty("Accept", "application/atom+xml");
            checkConnection.setConnectTimeout(Integer.parseInt(getGuvnorConnectTimeout()));
            checkConnection.setReadTimeout(Integer.parseInt(getGuvnorReadTimeout()));
            applyAuth(checkConnection);
            checkConnection.connect();
            if (checkConnection.getResponseCode() == 200) {

                XMLInputFactory factory = XMLInputFactory.newInstance();
                XMLStreamReader reader = factory.createXMLStreamReader(checkConnection.getInputStream());

                boolean foundFormFormat = false;
                while (reader.hasNext()) {
                    if (reader.next() == XMLStreamReader.START_ELEMENT) {
                        if ("format".equals(reader.getLocalName())) {
                            reader.next();
                            String pname = reader.getElementText();
                            if ("flt".equalsIgnoreCase(pname)) {
                                foundFormFormat = true;
                                break;
                            }
                        }
                    }
                }
                return foundFormFormat;
            }
        }
    } catch (Exception e) {
        logger.error("Exception checking template url : " + e.getMessage());
        return false;
    }
    logger.info("Could not find process template for: " + templateName);
    return false;
}

From source file:org.sogrey.frame.utils.FileUtil.java

/**
 * ????.//from   w  w w. j a v  a  2 s  .com
 *
 * @param url
 *         ?
 *
 * @return ??
 */
public static String getRealFileNameFromUrl(String url) {
    String name = null;
    try {
        if (StrUtil.isEmpty(url)) {
            return name;
        }

        URL mUrl = new URL(url);
        HttpURLConnection mHttpURLConnection = (HttpURLConnection) mUrl.openConnection();
        mHttpURLConnection.setConnectTimeout(5 * 1000);
        mHttpURLConnection.setRequestMethod("GET");
        mHttpURLConnection.setRequestProperty("Accept",
                "image/gif, image/jpeg, image/pjpeg, image/pjpeg, "
                        + "application/x-shockwave-flash, application/xaml+xml, "
                        + "application/vnd.ms-xpsdocument, application/x-ms-xbap, "
                        + "application/x-ms-application, application/vnd.ms-excel, "
                        + "application/vnd.ms-powerpoint, application/msword, */*");
        mHttpURLConnection.setRequestProperty("Accept-Language", "zh-CN");
        mHttpURLConnection.setRequestProperty("Referer", url);
        mHttpURLConnection.setRequestProperty("Charset", "UTF-8");
        mHttpURLConnection.setRequestProperty("User-Agent", "");
        mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive");
        mHttpURLConnection.connect();
        if (mHttpURLConnection.getResponseCode() == 200) {
            for (int i = 0;; i++) {
                String mine = mHttpURLConnection.getHeaderField(i);
                if (mine == null) {
                    break;
                }
                if ("content-disposition".equals(mHttpURLConnection.getHeaderFieldKey(i).toLowerCase())) {
                    Matcher m = Pattern.compile(".*filename=(.*)").matcher(mine.toLowerCase());
                    if (m.find())
                        return m.group(1).replace("\"", "");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        LogUtil.e(FileUtil.class, "???");
    }
    return name;
}

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

public void sendChangesToCozy() {
    List<Contact> unSyncedContacts = Contact.getAllUnsynced();
    int i = 0;/*from w  w  w.  jav a 2 s  .  c om*/
    for (Contact contact : unSyncedContacts) {
        URL urlO = null;
        try {
            JSONObject jsonObject = contact.toJsonObject();

            System.out.println(jsonObject.toString());

            mBuilder.setProgress(unSyncedContacts.size(), i + 1, false);
            mBuilder.setContentText("Syncing " + jsonObject.getString("docType") + ":");
            mNotifyManager.notify(notification_id, mBuilder.build());
            EventBus.getDefault()
                    .post(new ContactSyncEvent(SYNC_MESSAGE, getString(R.string.lbl_contacts_ongoing_sync)));
            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");
                contact.setRemoteId(result);
                contact.save();
            }

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

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