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:cn.leancloud.diamond.server.service.NotifyService.java

/**
 * http get/*from   w  ww  .  j  a v  a2 s .  c  o m*/
 * 
 * @param urlString
 * @return
 */
private String invokeURL(String urlString) {
    HttpURLConnection conn = null;
    URL url = null;
    try {
        url = new URL(urlString);
        conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(TIMEOUT);
        conn.setReadTimeout(TIMEOUT);
        conn.setRequestMethod("GET");
        conn.connect();
        InputStream urlStream = conn.getInputStream();
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(urlStream));
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } finally {
            if (reader != null)
                reader.close();
        }
        return sb.toString();

    } catch (Exception e) {
        log.error("http,url=" + urlString, e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
    return "error";
}

From source file:com.taobao.diamond.server.service.NotifyService.java

/**
 * http get//from   w w w. j  a va 2s  .c o  m
 * 
 * @param urlString
 * @return
 */
private String invokeURL(String urlString) {
    HttpURLConnection conn = null;
    URL url = null;
    try {
        url = new URL(urlString);
        conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(TIMEOUT);
        conn.setReadTimeout(TIMEOUT);
        conn.setRequestMethod("GET");
        conn.connect();
        InputStream urlStream = conn.getInputStream();
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(urlStream));
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } finally {
            if (reader != null)
                reader.close();
        }
        return sb.toString();

    } catch (Exception e) {
        log.error("http,url=" + urlString, e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
    return "error";
}

From source file:com.scut.easyfe.network.kjFrame.http.HttpConnectStack.java

private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    int timeoutMs = request.getTimeoutMs();
    connection.setConnectTimeout(timeoutMs);
    connection.setReadTimeout(timeoutMs);
    connection.setUseCaches(false);/*from  w w  w  .jav a2 s .  c o  m*/
    connection.setDoInput(true);

    // use caller-provided custom SslSocketFactory, if any, for HTTPS
    if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
        ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory);
    }

    return connection;
}

From source file:io.indy.drone.service.ScheduledService.java

private String httpGet(String path) throws IOException {
    BufferedReader reader = null;
    try {/* w ww  .  j av  a2s  .c  om*/
        URL url = new URL(path);
        HttpURLConnection c = (HttpURLConnection) url.openConnection();

        c.setRequestMethod("GET");
        c.setReadTimeout(15000);
        c.connect();

        reader = new BufferedReader(new InputStreamReader(c.getInputStream()));
        StringBuilder buf = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            buf.append(line + "\n");
        }

        return buf.toString();

    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}

From source file:cn.garymb.wechatmoments.common.OkHttpStack.java

private HttpURLConnection openOkHttpURLConnection(OkUrlFactory factory, URL url, Request<?> request)
        throws IOException {
    HttpURLConnection connection = factory.open(url);
    int timeoutMs = request.getTimeoutMs();
    connection.setConnectTimeout(timeoutMs);
    connection.setReadTimeout(timeoutMs);
    connection.setUseCaches(false);/*from   w  w  w  .j a va2s  .co  m*/
    connection.setDoInput(true);

    // use caller-provided custom SslSocketFactory, if any, for HTTPS
    if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
        ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory);
    }

    return connection;
}

From source file:com.couchbase.devex.CouchDBConfig.java

@Override
public Observable<Document> startImport() {
    BufferedReader inp2 = null;/* w  w w  .  ja  v  a 2  s  .co  m*/
    try {
        URL url = new URL(downloadURL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");
        // assume this is going to be a big file...
        conn.setReadTimeout(0);
        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
        }

        inp2 = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    Observable.from(inp2.lines()::iterator).flatMap(s -> {
        JsonNode node = null;
        if (s.endsWith("\"rows\":[")) {
            // first line, find total rows, offset
            s = s.concat("]}");
            try {
                node = om.readTree(s.toString());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            long totalRows = node.get(TOTAL_ROWS_PROPERTY).asLong();
            long offset = node.get(OFFSET_PROPERTY).asLong();
            log.info(String.format("Query starting at offset %d for a total of %d rows.", offset, totalRows));
            return Observable.empty();
        } else if (s.length() == 2) {
            // last line, do nothing
            log.info("end of the feed.");
            return Observable.empty();
        } else {
            try {
                if (s.endsWith(",")) {
                    node = om.readTree(s.substring(0, s.length() - 1).toString());
                } else {
                    node = om.readTree(s.toString());
                }
                String key = node.get("key").asText();
                String jsonDoc = node.get("doc").toString();
                Document doc = RawJsonDocument.create(key, jsonDoc);
                return Observable.just(doc);
            } catch (IOException e) {
                return Observable.error(e);
            }
        }

    });
    return Observable.empty();
}

From source file:com.example.socketmobile.android.warrantychecker.network.UserRegistration.java

private Object fetchWarranty(String id, String authString, String query) throws IOException {
    InputStream is = null;/*from w w w .j  a v a2s. co  m*/
    RegistrationApiResponse result = null;
    RegistrationApiErrorResponse errorResult = null;
    String authHeader = "Basic " + Base64.encodeToString(authString.getBytes(), Base64.NO_WRAP);

    try {
        URL url = new URL(baseUrl + id + "/registrations");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(10000 /* milliseconds */);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        writer.write(query);
        writer.flush();
        writer.close();
        os.close();

        conn.connect();
        int response = conn.getResponseCode();

        Log.d(TAG, "Warranty query responded: " + response);
        switch (response / 100) {
        case 2:
            is = conn.getInputStream();
            RegistrationApiResponse.Reader reader = new RegistrationApiResponse.Reader();
            result = reader.readJsonStream(is);
            break;
        case 4:
        case 5:
            is = conn.getErrorStream();

            RegistrationApiErrorResponse.Reader errorReader = new RegistrationApiErrorResponse.Reader();
            errorResult = errorReader.readErrorJsonStream(is);

            break;
        }

    } catch (IOException e) {
        e.printStackTrace();
        return null;
    } finally {
        if (is != null) {
            is.close();
        }
    }
    return (result != null) ? result : errorResult;
}

From source file:fyp.project.asyncTask.Http_GetPost.java

public void POST(String url, String val) throws IOException {
    HttpURLConnection urlConnection = null;
    try {//from w  w w  .j a v  a  2 s  .  co m
        URL url2 = new URL(url);
        urlConnection = (HttpURLConnection) url2.openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setReadTimeout(5000);
        urlConnection.setConnectTimeout(10000);
        urlConnection.setDoOutput(true);
        String data = val;
        OutputStream out = urlConnection.getOutputStream();
        out.write(data.getBytes());
        out.flush();
        out.close();

        int responseCode = urlConnection.getResponseCode();
        if (responseCode == 200) {
            InputStream is = urlConnection.getInputStream();
            String result = convertInputStreamToString(is);
            webpage_output = result;

        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        urlConnection.disconnect();
    }

}

From source file:com.lark.http.LarkHurlStack.java

/**
* Opens an {@link HttpURLConnection} with parameters.
* @param url/*from  w  ww. j  av a2s .co m*/
* @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())) {
        HttpsTrustManager.allowAllSSL();//TODO really support?
    }

    return connection;
}

From source file:com.nostra13.universalimageloader.core.download.BaseImageDownloader.java

/**
 * Create {@linkplain HttpURLConnection HTTP connection} for incoming URL
 *
 * @param url   URL to connect to//  w  ww. jav  a 2  s.  c  o m
 * @param extra Auxiliary object which was passed to {@link DisplayImageOptions.Builder#extraForDownloader(Object)
 *              DisplayImageOptions.extraForDownloader(Object)}; can be null
 * @return {@linkplain HttpURLConnection Connection} for incoming URL. Connection isn't established so it still configurable.
 * @throws IOException if some I/O error occurs during network request or if no InputStream could be created for
 *                     URL.
 */
protected HttpURLConnection createConnection(String url, Object extra) throws IOException {
    String encodedUrl = Uri.encode(url, ALLOWED_URI_CHARS);
    HttpURLConnection conn = (HttpURLConnection) new URL(encodedUrl).openConnection();
    conn.setConnectTimeout(connectTimeout);
    conn.setReadTimeout(readTimeout);
    return conn;

}