Example usage for java.net HttpURLConnection setReadTimeout

List of usage examples for java.net HttpURLConnection setReadTimeout

Introduction

In this page you can find the example usage for java.net HttpURLConnection setReadTimeout.

Prototype

public void setReadTimeout(int timeout) 

Source Link

Document

Sets the read timeout to a specified timeout, in milliseconds.

Usage

From source file:com.edgenius.wiki.service.impl.NotifyMQConsumer.java

public void handleMessage(Object msg) {
    NotifyMQObject mqObj;//from w ww . j a va2  s  . c o  m
    try {
        if (msg instanceof NotifyMQObject) {
            mqObj = (NotifyMQObject) msg;
            if (mqObj.getType() == NotifyMQObject.TYPE_SYSTEM_STATUS_CHECK) {
                //send a http response to confirm JMS received
                String url = WebUtil.getHostAppURL() + "status?uuid=" + mqObj.getSpaceUname();
                try {
                    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
                    conn.setRequestMethod("GET");
                    conn.setReadTimeout(20000);
                    if (log.isDebugEnabled()) {
                        String uuid = IOUtils.toString(conn.getInputStream());
                        log.debug("Recieved system status JMS check UUID {}", uuid);
                    }
                    if (HttpURLConnection.HTTP_OK != conn.getResponseCode()) {
                        log.warn("Unable get response from system status JMS  confirm URL {}", url);
                    }
                } catch (Exception e) {
                    log.error("Unable to send satus confirm URL " + url, e);
                }
                return;
            }
            securityService.proxyLogin(mqObj.getUsername());

            if (mqObj.getType() == NotifyMQObject.TYPE_PAGE_UPDATE) {
                sendPageUpdateNodification(mqObj.getPageUid());
            } else if (mqObj.getType() == NotifyMQObject.TYPE_SPACE_REMOVE) {
                sendSpaceRemovingNotification(mqObj.getSpace(), mqObj.getRemoveDelayHours());
            } else if (mqObj.getType() == NotifyMQObject.TYPE_COMMENT_NOTIFY) {
                sendPageCommentsNotification(mqObj.getUsername(), mqObj.getPageUid(), mqObj.getCommentUid());
            } else if (mqObj.getType() == NotifyMQObject.TYPE_EXT_LINK_BLOG) {
                syncExtBlog(mqObj.getSpaceUname(), mqObj.getBlogMeta(), mqObj.getSyncLimit());
            } else if (mqObj.getType() == NotifyMQObject.TYPE_EXT_POST) {
                postBlog(mqObj.getBlogMeta(), mqObj.getId());
            } else if (mqObj.getType() == NotifyMQObject.TYPE_EXT_POST_COMMENT) {
                postBlogComment(mqObj.getBlogMeta(), mqObj.getId());
            } else if (mqObj.getType() == NotifyMQObject.TYPE_EXT_REMOVE_POST) {
                removeBlogPost(mqObj.getUsername(), mqObj.getBlogMeta(), mqObj.getId());
            } else if (mqObj.getType() == NotifyMQObject.TYPE_SPACE_MEUN_UPDATED) {
                updateSpaceMenu(mqObj.getSpaceUname());
            }
        } else {
            AuditLogger.error("Unexpected object in Index Counsumer " + msg);
            return;
        }
    } finally {
        securityService.proxyLogout();
    }

}

From source file:cm.aptoide.pt.util.NetworkUtils.java

public BufferedInputStream getInputStream(String url, String username, String password, Context mctx)
        throws IOException {

    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();

    if (username != null && password != null) {
        String basicAuth = "Basic "
                + new String(Base64.encode((username + ":" + password).getBytes(), Base64.NO_WRAP));
        connection.setRequestProperty("Authorization", basicAuth);
    }/*from   ww w .  j a  v a  2 s .  co  m*/
    connection.setConnectTimeout(TIME_OUT);
    connection.setReadTimeout(TIME_OUT);
    connection.setRequestProperty("User-Agent", getUserAgentString(mctx));
    System.out.println("Using user-agent: " + (getUserAgentString(mctx)));
    BufferedInputStream bis = new BufferedInputStream(connection.getInputStream(), 8 * 1024);

    //      if(ApplicationAptoide.DEBUG_MODE)
    Log.i("Aptoide-NetworkUtils", "Getting: " + url);

    return bis;

}

From source file:com.amazonaws.http.UrlHttpClient.java

void configureConnection(HttpRequest request, HttpURLConnection connection) {
    // configure the connection
    connection.setConnectTimeout(config.getConnectionTimeout());
    connection.setReadTimeout(config.getSocketTimeout());
    // disable redirect and cache
    connection.setInstanceFollowRedirects(false);
    connection.setUseCaches(false);//from  www.j  a  v a2 s.c o m
    // is streaming
    if (request.isStreaming()) {
        connection.setChunkedStreamingMode(0);
    }

    // configure https connection
    if (connection instanceof HttpsURLConnection) {
        final HttpsURLConnection https = (HttpsURLConnection) connection;

        // disable cert check
        /*
         * Commented as per https://support.google.com/faqs/answer/6346016. Uncomment for testing.
        if (System.getProperty(DISABLE_CERT_CHECKING_SYSTEM_PROPERTY) != null) {
        disableCertificateValidation(https);
        }
        */

        if (config.getTrustManager() != null) {
            enableCustomTrustManager(https);
        }
    }
}

From source file:com.wanikani.wklib.Connection.java

private void setTimeouts(HttpURLConnection conn) {
    conn.setConnectTimeout(CONNECT_TIMEOUT);
    conn.setReadTimeout(READ_TIMEOUT);
}

From source file:org.digitalcampus.oppia.task.DownloadCourseTask.java

@Override
protected Payload doInBackground(Payload... params) {
    Payload payload = params[0];//from w w w .  j  av a  2  s .co  m

    Course dm = (Course) payload.getData().get(0);
    DownloadProgress dp = new DownloadProgress();
    try {
        HTTPConnectionUtils client = new HTTPConnectionUtils(ctx);

        String url = client.createUrlWithCredentials(dm.getDownloadUrl());

        Log.d(TAG, "Downloading:" + url);

        URL u = new URL(url);
        HttpURLConnection c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.setDoOutput(true);
        c.connect();
        c.setConnectTimeout(
                Integer.parseInt(prefs.getString(ctx.getString(R.string.prefs_server_timeout_connection),
                        ctx.getString(R.string.prefServerTimeoutConnection))));
        c.setReadTimeout(Integer.parseInt(prefs.getString(ctx.getString(R.string.prefs_server_timeout_response),
                ctx.getString(R.string.prefServerTimeoutResponse))));

        int fileLength = c.getContentLength();

        String localFileName = dm.getShortname() + "-" + String.format("%.0f", dm.getVersionId()) + ".zip";

        dp.setMessage(localFileName);
        dp.setProgress(0);
        publishProgress(dp);

        Log.d(TAG, "saving to: " + localFileName);

        FileOutputStream f = new FileOutputStream(new File(MobileLearning.DOWNLOAD_PATH, localFileName));
        InputStream in = c.getInputStream();

        byte[] buffer = new byte[1024];
        int len1 = 0;
        long total = 0;
        int progress = 0;
        while ((len1 = in.read(buffer)) > 0) {
            total += len1;
            progress = (int) (total * 100) / fileLength;
            if (progress > 0) {
                dp.setProgress(progress);
                publishProgress(dp);
            }
            f.write(buffer, 0, len1);
        }
        f.close();

        dp.setProgress(100);
        publishProgress(dp);
        dp.setMessage(ctx.getString(R.string.download_complete));
        publishProgress(dp);
        payload.setResult(true);
    } catch (ClientProtocolException cpe) {
        if (!MobileLearning.DEVELOPER_MODE) {
            BugSenseHandler.sendException(cpe);
        } else {
            cpe.printStackTrace();
        }
        payload.setResult(false);
        payload.setResultResponse(ctx.getString(R.string.error_connection));
    } catch (SocketTimeoutException ste) {
        if (!MobileLearning.DEVELOPER_MODE) {
            BugSenseHandler.sendException(ste);
        } else {
            ste.printStackTrace();
        }
        payload.setResult(false);
        payload.setResultResponse(ctx.getString(R.string.error_connection));
    } catch (IOException ioe) {
        if (!MobileLearning.DEVELOPER_MODE) {
            BugSenseHandler.sendException(ioe);
        } else {
            ioe.printStackTrace();
        }
        payload.setResult(false);
        payload.setResultResponse(ctx.getString(R.string.error_connection));
    }

    return payload;
}

From source file:net.servicestack.client.JsonServiceClient.java

public HttpURLConnection createRequest(String requestUrl, String httpMethod, byte[] requestBody,
        String requestType) {/*  w w w  .  ja  va 2s  . c  om*/
    try {
        URL url = new URL(requestUrl);

        HttpURLConnection req = (HttpURLConnection) url.openConnection();
        req.setDoOutput(true);

        if (timeoutMs != null) {
            req.setConnectTimeout(timeoutMs);
            req.setReadTimeout(timeoutMs);
        }

        req.setRequestMethod(httpMethod);
        req.setRequestProperty(HttpHeaders.Accept, MimeTypes.Json);

        if (requestType != null) {
            req.setRequestProperty(HttpHeaders.ContentType, requestType);
        }

        if (requestBody != null) {
            req.setRequestProperty(HttpHeaders.ContentLength, Integer.toString(requestBody.length));
            DataOutputStream wr = new DataOutputStream(req.getOutputStream());
            wr.write(requestBody);
            wr.flush();
            wr.close();
        }

        if (RequestFilter != null) {
            RequestFilter.exec(req);
        }

        if (GlobalRequestFilter != null) {
            GlobalRequestFilter.exec(req);
        }

        return req;

    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.attask.api.StreamClient.java

private HttpURLConnection createConnection(String spec, String method) throws IOException {
    URL url = new URL(spec);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    if (conn instanceof HttpsURLConnection) {
        ((HttpsURLConnection) conn).setHostnameVerifier(HOSTNAME_VERIFIER);
    }/*from www  .  j  a  v  a  2s .c o m*/

    conn.setAllowUserInteraction(false);
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setConnectTimeout(60000);
    conn.setReadTimeout(300000);
    conn.connect();

    return conn;
}

From source file:com.rapleaf.api.personalization.RapleafApi.java

protected String bulkJsonResponse(String urlStr, String list) throws Exception {
    URL url = new URL(urlStr);
    HttpURLConnection handle = (HttpURLConnection) url.openConnection();
    handle.setRequestProperty("User-Agent", getUserAgent());
    handle.setRequestProperty("Content-Type", "application/json");
    handle.setConnectTimeout(timeout);/*  w  ww . j ava 2  s.  c  o  m*/
    handle.setReadTimeout(bulkTimeout);
    handle.setDoOutput(true);
    handle.setRequestMethod("POST");
    OutputStreamWriter wr = new OutputStreamWriter(handle.getOutputStream());
    wr.write(list);
    wr.flush();
    BufferedReader rd = new BufferedReader(new InputStreamReader(handle.getInputStream()));
    String line = rd.readLine();
    StringBuilder sb = new StringBuilder();
    while (line != null) {
        sb.append(line);
        line = rd.readLine();
    }
    wr.close();
    rd.close();

    int responseCode = handle.getResponseCode();
    if (responseCode < 200 || responseCode > 299) {
        throw new Exception("Error Code " + responseCode + ": " + sb.toString());
    }

    return sb.toString();
}

From source file:com.hp.hpl.jena.sparql.engine.http.HttpQuery.java

private void applyTimeouts(HttpURLConnection conn) {
    if (connectTimeout > 0) {
        conn.setConnectTimeout(connectTimeout);
    }/*from   w w w .jav a2 s . c  om*/
    if (readTimeout > 0) {
        conn.setReadTimeout(readTimeout);
    }
}

From source file:com.francetelecom.clara.cloud.mvn.consumer.maven.MavenDeployer.java

/**
 * Verify that a given url can be reached
 * /*  w  w  w.  j ava 2  s  .  co  m*/
 * @param url
 * @return true if valid, false if not
 */
boolean isValidUrl(URL url) {
    logger.debug("Testing url: " + url);
    HttpURLConnection huc = null;
    int responseCode = 0;
    try {
        huc = openHttpUrlConnection(url);
        huc.setRequestMethod("HEAD");
        // set a long enough timeout to be protected against slow
        // network/server response time
        huc.setReadTimeout(30000);
        huc.connect();
        responseCode = huc.getResponseCode();
    } catch (IOException e) {
        logger.error("unable to test url " + url, e);
    } finally {
        if (huc != null)
            huc.disconnect();
    }
    boolean isValid = (responseCode == 200);
    if (!isValid)
        logger.warn("Http HEAD on Url " + url + " returns " + responseCode);
    return isValid;
}