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.pursuer.reader.easyrss.network.NetworkClient.java

public InputStream doGetStream(final String url) throws Exception {
    final HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setConnectTimeout(40 * 1000);//from w  w  w  .  j  a va2s .c o m
    conn.setReadTimeout(30 * 1000);
    conn.setRequestMethod("GET");
    if (auth != null) {
        conn.setRequestProperty("Authorization", "GoogleLogin auth=" + auth);
    }
    try {
        final int resStatus = conn.getResponseCode();
        if (resStatus == HttpStatus.SC_UNAUTHORIZED) {
            ReaderAccountMgr.getInstance().invalidateAuth();
        }
        if (resStatus != HttpStatus.SC_OK) {
            throw new NetworkException("Invalid HTTP status " + resStatus + ": " + url + ".");
        }
    } catch (final Exception exception) {
        if (exception.getMessage() != null && exception.getMessage().contains("authentication")) {
            ReaderAccountMgr.getInstance().invalidateAuth();
        }
        throw exception;
    }
    return conn.getInputStream();
}

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

private Object fetchWarranty(String id, String authString, String query) throws IOException {
    InputStream is = null;/*ww w. j  a va 2  s .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 + "?" + query);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(10000 /* milliseconds */);
        //conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setDoOutput(false);

        conn.connect();
        int response = conn.getResponseCode();
        Log.d(TAG, "WarrantyCheck 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 (UnsupportedEncodingException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        return null;
    } finally {
        if (is != null) {
            is.close();
        }
    }
    return (result != null) ? result : errorResult;
}

From source file:com.pursuer.reader.easyrss.network.NetworkClient.java

public InputStream doPostStream(final String url, final String params) throws IOException, NetworkException {
    final HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setConnectTimeout(40 * 1000);//from  www.  j  a v  a  2s . co  m
    conn.setReadTimeout(30 * 1000);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    if (auth != null) {
        conn.setRequestProperty("Authorization", "GoogleLogin auth=" + auth);
    }
    conn.setDoInput(true);
    conn.setDoOutput(true);
    final OutputStream output = conn.getOutputStream();
    output.write(params.getBytes());
    output.flush();
    output.close();

    conn.connect();
    try {
        final int resStatus = conn.getResponseCode();
        if (resStatus == HttpStatus.SC_UNAUTHORIZED) {
            ReaderAccountMgr.getInstance().invalidateAuth();
        }
        if (resStatus != HttpStatus.SC_OK) {
            throw new NetworkException("Invalid HTTP status " + resStatus + ": " + url + ".");
        }
    } catch (final IOException exception) {
        if (exception.getMessage() != null && exception.getMessage().contains("authentication")) {
            ReaderAccountMgr.getInstance().invalidateAuth();
        }
        throw exception;
    }
    return conn.getInputStream();
}

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

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

    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.roadwarrior.vtiger.client.NetworkUtilities.java

/**
 * Connects to the  server, authenticates the provided username and
 * password.//ww w . j a  v a  2 s .  c o m
 * 
 * @param username The user's username
 * @param password The user's password
 * @return String The authentication token returned by the server (or null)
 */
public static String authenticate(String username, String accessKey, String base_url) {
    String token = null;
    String hash = null;
    authenticate_log_text = "authenticate()\n";
    AUTH_URI = base_url + "/webservice.php";
    authenticate_log_text = authenticate_log_text + "url: " + AUTH_URI + "?operation=getchallenge&username="
            + username + "\n";

    Log.d(TAG, "AUTH_URI : ");
    Log.d(TAG, AUTH_URI + "?operation=getchallenge&username=" + username);
    // =========== get challenge token ==============================
    ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    try {

        URL url;

        // HTTP GET REQUEST
        url = new URL(AUTH_URI + "?operation=getchallenge&username=" + username);
        HttpURLConnection con;
        con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("Content-length", "0");
        con.setUseCaches(false);
        // for some site that redirects based on user agent
        con.setInstanceFollowRedirects(true);
        con.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.15) Gecko/2009101600 Firefox/3.0.15");
        con.setAllowUserInteraction(false);
        int timeout = 20000;
        con.setConnectTimeout(timeout);
        con.setReadTimeout(timeout);
        con.connect();
        int status = con.getResponseCode();

        authenticate_log_text = authenticate_log_text + "Request status = " + status + "\n";
        switch (status) {
        case 200:
        case 201:
        case 302:
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            br.close();
            Log.d(TAG, "message body");
            Log.d(TAG, sb.toString());

            authenticate_log_text = authenticate_log_text + "body : " + sb.toString();
            if (status == 302) {
                authenticate_log_text = sb.toString();
                return null;
            }

            JSONObject result = new JSONObject(sb.toString());
            Log.d(TAG, result.getString("result"));
            JSONObject data = new JSONObject(result.getString("result"));
            token = data.getString("token");
            break;
        case 401:
            Log.e(TAG, "Server auth error: ");// + readResponse(con.getErrorStream()));
            authenticate_log_text = authenticate_log_text + "Server auth error";
            return null;
        default:
            Log.e(TAG, "connection status code " + status);// + readResponse(con.getErrorStream()));
            authenticate_log_text = authenticate_log_text + "connection status code :" + status;
            return null;
        }

    } catch (ClientProtocolException e) {
        Log.i(TAG, "getchallenge:http protocol error");
        Log.e(TAG, e.getMessage());
        authenticate_log_text = authenticate_log_text + "ClientProtocolException :" + e.getMessage() + "\n";
        return null;
    } catch (IOException e) {
        Log.e(TAG, "getchallenge: IO Exception");
        Log.e(TAG, e.getMessage());
        Log.e(TAG, AUTH_URI + "?operation=getchallenge&username=" + username);
        authenticate_log_text = authenticate_log_text + "getchallenge: IO Exception : " + e.getMessage() + "\n";
        return null;

    } catch (JSONException e) {
        Log.i(TAG, "json exception");
        authenticate_log_text = authenticate_log_text + "JSon exception\n";

        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }

    // ================= login ==================

    try {
        MessageDigest m = MessageDigest.getInstance("MD5");
        m.update(token.getBytes());
        m.update(accessKey.getBytes());
        hash = new BigInteger(1, m.digest()).toString(16);
        Log.i(TAG, "hash");
        Log.i(TAG, hash);
    } catch (NoSuchAlgorithmException e) {
        authenticate_log_text = authenticate_log_text + "MD5 => no such algorithm\n";
        e.printStackTrace();
    }

    try {
        String charset;
        charset = "utf-8";
        String query = String.format("operation=login&username=%s&accessKey=%s",
                URLEncoder.encode(username, charset), URLEncoder.encode(hash, charset));
        authenticate_log_text = authenticate_log_text + "login()\n";
        URLConnection connection = new URL(AUTH_URI).openConnection();
        connection.setDoOutput(true); // Triggers POST.
        int timeout = 20000;
        connection.setConnectTimeout(timeout);
        connection.setReadTimeout(timeout);
        connection.setAllowUserInteraction(false);
        connection.setRequestProperty("Accept-Charset", charset);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
        connection.setUseCaches(false);

        OutputStream output = connection.getOutputStream();
        try {
            output.write(query.getBytes(charset));
        } finally {
            try {
                output.close();
            } catch (IOException logOrIgnore) {

            }
        }
        Log.d(TAG, "Query written");
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();
        Log.d(TAG, "message post body");
        Log.d(TAG, sb.toString());
        authenticate_log_text = authenticate_log_text + "post message body :" + sb.toString() + "\n";
        JSONObject result = new JSONObject(sb.toString());

        String success = result.getString("success");
        Log.i(TAG, success);

        if (success == "true") {
            Log.i(TAG, result.getString("result"));
            Log.i(TAG, "sucesssfully logged  in is");
            JSONObject data = new JSONObject(result.getString("result"));
            sessionName = data.getString("sessionName");

            Log.i(TAG, sessionName);
            authenticate_log_text = authenticate_log_text + "successfully logged in\n";
            return token;
        } else {
            // success is false, retrieve error
            JSONObject data = new JSONObject(result.getString("error"));
            authenticate_log_text = "can not login :\n" + data.toString();

            return null;
        }
        //token = data.getString("token");
        //Log.i(TAG,token);
    } catch (ClientProtocolException e) {
        Log.d(TAG, "login: http protocol error");
        Log.d(TAG, e.getMessage());
        authenticate_log_text = authenticate_log_text + "HTTP Protocol error \n";
        authenticate_log_text = authenticate_log_text + e.getMessage() + "\n";
    } catch (IOException e) {
        Log.d(TAG, "login: IO Exception");
        Log.d(TAG, e.getMessage());

        authenticate_log_text = authenticate_log_text + "login: IO Exception \n";
        authenticate_log_text = authenticate_log_text + e.getMessage() + "\n";

    } catch (JSONException e) {
        Log.d(TAG, "JSON exception");
        // TODO Auto-generated catch block
        authenticate_log_text = authenticate_log_text + "JSON exception ";
        authenticate_log_text = authenticate_log_text + e.getMessage();
        e.printStackTrace();
    }
    return null;
    // ========================================================================

}

From source file:com.cannabiscoin.wallet.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> requestExchangeRates(final URL url, final String userAgent,
        final String... fields) {
    final long start = System.currentTimeMillis();

    HttpURLConnection connection = null;
    Reader reader = null;//  w w  w .  j av a 2  s. c o m

    try {

        Double btcRate = 0.0;
        boolean cryptsyValue = true;
        Object result = getCoinValueBTC();

        if (result == null) {
            result = getCoinValueBTC_BTER();
            cryptsyValue = false;
            if (result == null)
                return null;
        }
        btcRate = (Double) result;

        connection = (HttpURLConnection) url.openConnection();

        connection.setInstanceFollowRedirects(false);
        connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.addRequestProperty("User-Agent", userAgent);
        connection.connect();

        final int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024),
                    Constants.UTF_8);
            final StringBuilder content = new StringBuilder();
            Io.copy(reader, content);

            final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();

            final JSONObject head = new JSONObject(content.toString());
            for (final Iterator<String> i = head.keys(); i.hasNext();) {
                final String currencyCode = i.next();
                if (!"timestamp".equals(currencyCode)) {
                    final JSONObject o = head.getJSONObject(currencyCode);

                    for (final String field : fields) {
                        String rateStr = o.optString(field, null);

                        if (rateStr != null) {
                            try {
                                double rateForBTC = Double.parseDouble(rateStr);

                                rateStr = String.format("%.8f", rateForBTC * btcRate).replace(",", ".");

                                final BigInteger rate = GenericUtils.toNanoCoins(rateStr, 0);

                                if (rate.signum() > 0) {
                                    rates.put(currencyCode,
                                            new ExchangeRate(currencyCode, rate, url.getHost()));
                                    break;
                                }
                            } catch (final ArithmeticException x) {
                                log.warn("problem fetching {} exchange rate from {}: {}",
                                        new Object[] { currencyCode, url, x.getMessage() });
                            }

                        }
                    }
                }
            }

            log.info("fetched exchange rates from {}, took {} ms", url, (System.currentTimeMillis() - start));

            //Add Bitcoin information
            if (rates.size() == 0) {
                int i = 0;
                i++;
            } else {
                rates.put(CoinDefinition.cryptsyMarketCurrency,
                        new ExchangeRate(CoinDefinition.cryptsyMarketCurrency,
                                GenericUtils.toNanoCoins(String.format("%.8f", btcRate).replace(",", "."), 0),
                                cryptsyValue ? "pubapi.cryptsy.com" : "data.bter.com"));
                rates.put("m" + CoinDefinition.cryptsyMarketCurrency,
                        new ExchangeRate("m" + CoinDefinition.cryptsyMarketCurrency,
                                GenericUtils.toNanoCoins(
                                        String.format("%.5f", btcRate * 1000).replace(",", "."), 0),
                                cryptsyValue ? "pubapi.cryptsy.com" : "data.bter.com"));
            }

            return rates;
        } else {
            log.warn("http status {} when fetching {}", responseCode, url);
        }
    } catch (final Exception x) {
        log.warn("problem fetching exchange rates from " + url, x);
    } finally {

        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException x) {
                // swallow
            }
        }

        if (connection != null)
            connection.disconnect();
    }

    return null;
}

From source file:cm.aptoide.pt.LatestLikesComments.java

public Cursor getLikes() {
    endPointLikes = String.format(endPointLikes, repoName);
    MatrixCursor cursor = new MatrixCursor(new String[] { "_id", "apkid", "name", "like", "username" });

    try {/*from  ww w. ja v a2 s.c  o m*/
        HttpURLConnection connection = (HttpURLConnection) new URL(endPointLikes).openConnection();
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();

        JSONObject respJSON = new JSONObject(sb.toString());
        JSONArray array = respJSON.getJSONArray("listing");

        for (int i = 0; i != array.length(); i++) {

            String apkid = ((JSONObject) array.get(i)).getString("apkid");
            String name = ((JSONObject) array.get(i)).getString("name");
            String like = ((JSONObject) array.get(i)).getString("like");
            String username = ((JSONObject) array.get(i)).getString("username");
            if (username.equals("NOT_SIGNED_UP")) {
                username = "";
            }
            cursor.newRow().add(i).add(apkid).add(name).add(like).add(username);

        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return cursor;
}

From source file:mobi.espier.lgc.data.UploadHelper.java

private String doHttpPostAndGetResponse(String url, byte[] data) {
    if (TextUtils.isEmpty(url) || data == null || data.length < 1) {
        return null;
    }/*from   w  ww  . j a  v  a  2s.  co  m*/

    String response = null;
    try {
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setConnectTimeout(30000);
        conn.setReadTimeout(30000);
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", String.valueOf(data.length));
        OutputStream outStream = conn.getOutputStream();
        outStream.write(data);

        int mResponseCode = conn.getResponseCode();
        if (mResponseCode == 200) {
            response = getHttpResponse(conn);
        }
        conn.disconnect();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (SocketTimeoutException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return response;
}

From source file:com.snda.mymarket.providers.downloads.HurlStack.java

/**
 * Opens an {@link HttpURLConnection} with parameters.
 * @param url/*from   w ww  .j av a  2 s . co m*/
 * @return an open connection
 * @throws IOException
 */
private HttpURLConnection openConnection(URL url, HttpUriRequest request) throws IOException {
    HttpURLConnection connection = createConnection(url);

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

    return connection;
}

From source file:org.freshrss.easyrss.network.NetworkClient.java

private HttpURLConnection makeConnection(final String url) throws MalformedURLException, IOException {
    final HttpURLConnection httpURLConnection = (HttpURLConnection) (new URL(url).openConnection());
    httpURLConnection.setConnectTimeout(40 * 1000);
    httpURLConnection.setReadTimeout(30 * 1000);
    if (url.toLowerCase(Locale.US).startsWith("https://")) {
        final HttpsURLConnection httpsURLConnection = (HttpsURLConnection) httpURLConnection;
        httpsURLConnection.setSSLSocketFactory(this.sslSocketFactory);
    }// w  w w  .j a  v  a 2 s  .co  m
    return httpURLConnection;
}