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.esminis.server.library.service.server.installpackage.InstallerPackage.java

private void download(Context context, com.esminis.server.library.model.InstallPackage model, File fileOutput)
        throws Throwable {
    sendBroadcast(context, STATE_DOWNLOAD, 0);
    final HttpURLConnection connection = (HttpURLConnection) new URL(model.uri).openConnection();
    connection.setConnectTimeout(20000);
    connection.setReadTimeout(10000);/*from  w ww  .  ja  va2 s.  c om*/
    FileOutputStream output = null;
    try {
        output = new FileOutputStream(fileOutput);
        InputStream inputStream = connection.getInputStream();
        final float fileSize = (float) connection.getContentLength();
        byte[] buffer = new byte[1024 * 128];
        long count = 0;
        int n;
        long time = System.currentTimeMillis();
        while (-1 != (n = inputStream.read(buffer))) {
            count += n;
            output.write(buffer, 0, n);
            if (System.currentTimeMillis() - time >= 1000) {
                sendBroadcast(context, STATE_DOWNLOAD, (((float) count) / fileSize) * 0.99f);
                time = System.currentTimeMillis();
            }
        }
        sendBroadcast(context, STATE_DOWNLOAD, 0.99f);
    } finally {
        connection.disconnect();
        if (output != null) {
            try {
                output.close();
            } catch (IOException ignored) {
            }
        }
    }
    if (model.hash != null && !model.hash.equals(Utils.hash(fileOutput))) {
        throw new Exception("Downloaded file was corrupted: " + model.uri);
    }
    sendBroadcast(context, STATE_DOWNLOAD, 1);
}

From source file:eu.codeplumbers.cosi.api.tasks.CheckDesignDocumentsTask.java

private String createDesignDocument(String docType) {
    String returnResult = "";
    JSONObject docTypeMap = new JSONObject();
    try {/*  w w  w . j  a v  a  2 s  .  c om*/
        docTypeMap.put("map", "function (doc) { if (doc.docType.toLowerCase() === '" + docType
                + "') { filter = function (doc) { return emit(doc._id, doc); }; filter(doc); }}");

        URL urlO = getCosiUrl(docType);

        String 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
        OutputStream os = conn.getOutputStream();
        os.write(docTypeMap.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();

        if (result.contains("success")) {
            returnResult = "";
        } else {
            returnResult = result;
        }

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

    } catch (UnsupportedEncodingException e) {
        returnResult = e.getLocalizedMessage();
        e.printStackTrace();
    } catch (ProtocolException e) {
        returnResult = e.getLocalizedMessage();
        e.printStackTrace();
    } catch (IOException e) {
        returnResult = e.getLocalizedMessage();
        e.printStackTrace();
    } catch (JSONException e) {
        returnResult = e.getLocalizedMessage();
        e.printStackTrace();
    }

    return returnResult;
}

From source file:net.peterkuterna.appengine.apps.devoxxsched.util.Md5Calculator.java

private byte[] getResponse(final String requestUri) {
    try {/*from  ww w.ja va  2s .c om*/
        URL url = new URL(requestUri);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("User-agent", "Devoxx Schedule AppEngine Backend");
        connection.setDoOutput(true);
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(120 * 1000);
        connection.setRequestProperty("Cache-Control", "no-cache,max-age=0");
        connection.setRequestProperty("Pragma", "no-cache");
        InputStream response = connection.getInputStream();
        log.info("response = " + connection.getResponseCode());
        if (connection.getResponseCode() == 200) {
            return IOUtils.toByteArray(response);
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:ch.pec0ra.mobilityratecalculator.DistanceCalculator.java

private String downloadUrl(String myurl) throws IOException {
    InputStream is = null;/*from   w w w  . j  a v a 2  s  .c o m*/

    try {
        URL url = new URL(myurl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        // Starts the query
        conn.connect();
        conn.getResponseCode();
        is = conn.getInputStream();

        String responseAsString = CharStreams.toString(new InputStreamReader(is));
        return responseAsString;

        // Makes sure that the InputStream is closed after the app is
        // finished using it.
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:com.predic8.membrane.core.interceptor.balancer.NodeOnlineChecker.java

private List<BadNode> pingOfflineNodes() {
    ArrayList<BadNode> onlineNodes = new ArrayList<BadNode>();

    for (BadNode node : offlineNodes) {
        URL url = null;// w  w  w . j  a va2 s .co m
        try {
            url = new URL(node.getNode().getHost());
        } catch (MalformedURLException ignored) {
            continue;
        }
        try {
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
            urlConn.setConnectTimeout(pingTimeoutInSeconds * 1000);
            urlConn.connect();
            if (urlConn.getResponseCode() == HttpURLConnection.HTTP_OK)
                onlineNodes.add(node);
        } catch (IOException ignored) {
            continue;
        }
    }

    return onlineNodes;
}

From source file:com.streamsets.datacollector.updatechecker.UpdateChecker.java

@Override
public void run() {
    updateInfo = null;/*from  ww  w.j  av a 2 s . co  m*/
    PipelineState ps;
    try {
        ps = runner.getState();
    } catch (PipelineStoreException e) {
        LOG.warn(Utils.format("Cannot get pipeline state: '{}'", e.toString()), e);
        return;
    }
    if (ps.getStatus() == PipelineStatus.RUNNING) {
        if (url != null) {
            Map uploadInfo = getUploadInfo();
            if (uploadInfo != null) {
                HttpURLConnection conn = null;
                try {
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(2000);
                    conn.setReadTimeout(2000);
                    conn.setDoOutput(true);
                    conn.setDoInput(true);
                    conn.setRequestProperty("content-type", APPLICATION_JSON_MIME);
                    ObjectMapperFactory.getOneLine().writeValue(conn.getOutputStream(), uploadInfo);
                    if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                        String responseContentType = conn.getHeaderField("content-type");
                        if (APPLICATION_JSON_MIME.equals(responseContentType)) {
                            updateInfo = ObjectMapperFactory.get().readValue(conn.getInputStream(), Map.class);
                        } else {
                            LOG.trace("Got invalid content-type '{}' from from update-check server",
                                    responseContentType);
                        }
                    } else {
                        LOG.trace("Got '{} : {}' from update-check server", conn.getResponseCode(),
                                conn.getResponseMessage());
                    }
                } catch (Exception ex) {
                    LOG.trace("Could not do an update check: {}", ex.toString(), ex);
                } finally {
                    if (conn != null) {
                        conn.disconnect();
                    }
                }
            }
        }
    }
}

From source file:com.zlk.bigdemo.android.volley.toolbox.HurlStack.java

/**
 * Opens an {@link HttpURLConnection} with parameters.
 * @param url//from   w  w  w  .  j  a  v a 2s . com
 * @return an open connection
 * @throws IOException
 */
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
    HttpURLConnection connection = createConnection(url);

    int timeoutMs = request.getTimeoutMs();
    connection.setConnectTimeout(timeoutMs);
    connection.setReadTimeout(timeoutMs);
    connection.setUseCaches(false);
    connection.setDoInput(true);

    // use caller-provided custom SslSocketFactory, if any, for HTTPS
    if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory);
    }

    return connection;
}

From source file:eu.codeplumbers.cosi.api.tasks.CheckDesignDocumentsTask.java

@Override
protected String doInBackground(String... docTypes) {
    errorMessage = "";
    for (int i = 0; i < docTypes.length; i++) {
        String docType = docTypes[i].toLowerCase();
        publishProgress("Checking design: " + docType);

        URL urlO = null;/*from   www  . ja  va 2  s  .  c om*/
        try {

            // using all view can break notes, files app in cozy
            urlO = getCosiUrl(docType);

            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();

            if (result != "") {
                errorMessage = createDesignDocument(docType);
                if (errorMessage != "") {
                    return errorMessage;
                } else {
                    errorMessage = "";
                }
            } else {
                errorMessage = "Failed to parse API response";
                return errorMessage;
            }

            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();
        }
    }

    return errorMessage;
}

From source file:com.anyonavinfo.commonuserregister.MainActivity.java

/**
 * Post?/*  ww w  .j  a  va 2 s . c om*/
 */
public static String doPost(String urlStr, File file) {
    URL url = null;
    HttpURLConnection conn = null;
    InputStream is = null;
    ByteArrayOutputStream baos = null;
    String BOUNDARY = UUID.randomUUID().toString(); //  ??
    String PREFIX = "--", LINE_END = "\r\n";
    String CONTENT_TYPE = "multipart/form-data"; // 

    try {
        url = new URL(urlStr);
        conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(15000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("POST");
        conn.setDoInput(true); // ??
        conn.setDoOutput(true); // ??
        conn.setUseCaches(false); // ??
        conn.setRequestProperty("encoding", "utf-8");
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);

        if (file != null) {
            /**
             * ?
             */
            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
            StringBuffer sb = new StringBuffer();
            sb.append(PREFIX);
            sb.append(BOUNDARY);
            sb.append(LINE_END);
            /**
             * ?? name???key ?key ??
             * filename??????
             */

            sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\""
                    + LINE_END);
            sb.append("Content-Type: application/octet-stream; charset=" + "utf-8" + LINE_END);
            sb.append(LINE_END);
            dos.write(sb.toString().getBytes());
            InputStream IS = new FileInputStream(file);
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = IS.read(bytes)) != -1) {
                dos.write(bytes, 0, len);
            }
            IS.close();
            dos.write(LINE_END.getBytes());
            byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
            dos.write(end_data);
            dos.flush();
        }

        if (conn.getResponseCode() == 200) {
            is = conn.getInputStream();
            baos = new ByteArrayOutputStream();
            int len = -1;
            byte[] buf = new byte[128];

            while ((len = is.read(buf)) != -1) {
                baos.write(buf, 0, len);
                Log.d("Sjj--->", len + "");
            }
            baos.flush();
            return baos.toString();
        } else {
            throw new RuntimeException(" responseCode is not 200 ... ");
        }

    } catch (Exception e) {
        // 
        if (e instanceof SocketTimeoutException) {
            return "SocketTimeoutException";
        } else if (e instanceof UnknownHostException) {
            return "UnknownHostException";
        }
        e.printStackTrace();
    } finally {
        try {
            if (is != null)
                is.close();
            if (baos != null)
                baos.close();
            if (conn != null) {
                conn.disconnect();
            }
        } catch (IOException e) {
        }
    }

    return null;
}

From source file:eu.codeplumbers.cosi.api.tasks.SyncDocumentTask.java

@Override
protected String doInBackground(JSONObject... jsonObjects) {
    for (int i = 0; i < jsonObjects.length; i++) {
        JSONObject jsonObject = jsonObjects[i];

        URL urlO = null;//from  ww w. java 2  s.  com
        try {
            publishProgress("Syncing " + jsonObject.getString("docType") + ":", i + "",
                    jsonObjects.length + "");
            String remoteId = jsonObject.getString("remoteId");
            String requestMethod = "";

            if (remoteId.isEmpty()) {
                urlO = new URL(url);
                requestMethod = "POST";
            } else {
                urlO = new URL(url + 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");
            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");

                if (jsonObject.get("docType").equals("Sms")) {
                    Sms sms = Sms.load(Sms.class, objectId);
                    sms.setRemoteId(result);
                    sms.save();
                }

                if (jsonObject.get("docType").equals("Note")) {
                    Note note = Note.load(Note.class, objectId);
                    note.setRemoteId(result);
                    note.save();
                }

                if (jsonObject.get("docType").equals("Call")) {
                    Call call = Call.load(Call.class, objectId);
                    call.setRemoteId(result);
                    call.save();
                }

                if (jsonObject.get("docType").equals("Expense")) {
                    Expense expense = Expense.load(Expense.class, objectId);
                    expense.setRemoteId(result);
                    expense.save();
                }
            }

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

        } catch (MalformedURLException e) {
            result = "error";
            e.printStackTrace();
            errorMessage = e.getLocalizedMessage();
        } catch (ProtocolException e) {
            result = "error";
            errorMessage = e.getLocalizedMessage();
            e.printStackTrace();
        } catch (IOException e) {
            result = "error";
            errorMessage = e.getLocalizedMessage();
            e.printStackTrace();
        } catch (JSONException e) {
            result = "error";
            errorMessage = e.getLocalizedMessage();
            e.printStackTrace();
        }
    }

    return result;
}