List of usage examples for java.net URLConnection setConnectTimeout
public void setConnectTimeout(int timeout)
From source file:org.arasthel.almeribus.utils.LoadFromWeb.java
public static String getUltimaVersion() { String mensaje = null;/*from w w w . j ava2 s. c om*/ try { URL url = new URL("http://arasthel.byethost14.com/almeribus/version.html?token=" + new Random().nextInt(Integer.MAX_VALUE)); URLConnection connection = url.openConnection(); connection.setUseCaches(false); connection.setConnectTimeout(10000); connection.setReadTimeout(15000); Scanner scan = new Scanner(connection.getInputStream()); StringBuilder strBuilder = new StringBuilder(); while (scan.hasNextLine()) { strBuilder.append(scan.nextLine()); } scan.close(); mensaje = strBuilder.toString(); } catch (Exception e) { } return mensaje; }
From source file:com.feathercoin.wallet.feathercoin.ExchangeRatesProvider.java
private static Map<String, ExchangeRate> getFeathercoinCharts() { final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>(); // Keep the BTC rate around for a bit Double btcRate = 0.0;//from w w w .j a va 2 s .c om try { /* String currencies[] = {"USD", "BTC", "RUR"}; String urls[] = {"https://btc-e.com/api/2/ftc_btc/ticker", "https://btc-e.com/api/2/10/ticker", "https://btc-e.com/api/2/ltc_rur/ticker"}; for(int i = 0; i < currencies.length; ++i) { final String currencyCode = currencies[i]; final URL URL = new URL(urls[i]); final URLConnection connection = URL.openConnection(); connection.setConnectTimeout(TIMEOUT_MS); connection.setReadTimeout(TIMEOUT_MS); connection.connect(); final StringBuilder content = new StringBuilder(); Reader reader = null; try { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024)); IOUtils.copy(reader, content); final JSONObject head = new JSONObject(content.toString()); JSONObject ticker = head.getJSONObject("ticker"); Double avg = ticker.getDouble("avg"); String euros = String.format("%.4f", avg); // Fix things like 3,1250 euros = euros.replace(",", "."); rates.put(currencyCode, new ExchangeRate(currencyCode, Utils.toNanoCoins(euros), URL.getHost())); if(currencyCode.equalsIgnoreCase("BTC")) btcRate = avg; } finally { if (reader != null) reader.close(); } }*/ // Handle FTC/USD special since we have to do maths URL URL = null; try { URL = new URL("https://btc-e.com/api/2/ftc_btc/ticker"); } catch (MalformedURLException e) { e.printStackTrace(); } URLConnection connection = URL.openConnection(); connection.setConnectTimeout(TIMEOUT_MS); connection.setReadTimeout(TIMEOUT_MS); connection.connect(); StringBuilder content = new StringBuilder(); Reader reader = null; try { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024)); IOUtils.copy(reader, content); final JSONObject head = new JSONObject(content.toString()); JSONObject ticker = head.getJSONObject("ticker"); Double avg = ticker.getDouble("avg"); // This is feathercoins priced in bitcoins btcRate = avg; String s_avg = String.format("%.4f", avg).replace(',', '.'); rates.put("BTC", new ExchangeRate("BTC", Utils.toNanoCoins(s_avg), URL.getHost())); } finally { if (reader != null) reader.close(); } // Handle FTC/USD special since we have to do maths URL = null; URL = new URL("https://btc-e.com/api/2/btc_usd/ticker"); connection = URL.openConnection(); connection.setConnectTimeout(TIMEOUT_MS); connection.setReadTimeout(TIMEOUT_MS); connection.connect(); content = new StringBuilder(); reader = null; try { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024)); IOUtils.copy(reader, content); final JSONObject head = new JSONObject(content.toString()); JSONObject ticker = head.getJSONObject("ticker"); Double avg = ticker.getDouble("avg"); // This is bitcoins priced in dollars. We want FTC! avg *= btcRate; String s_avg = String.format("%.4f", avg).replace(',', '.'); rates.put("USD", new ExchangeRate("USD", Utils.toNanoCoins(s_avg), URL.getHost())); } finally { if (reader != null) reader.close(); } // Handle FTC/BTC special since we have to do maths URL = new URL("https://btc-e.com/api/2/btc_eur/ticker"); connection = URL.openConnection(); connection.setConnectTimeout(TIMEOUT_MS); connection.setReadTimeout(TIMEOUT_MS); connection.connect(); content = new StringBuilder(); reader = null; try { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024)); IOUtils.copy(reader, content); final JSONObject head = new JSONObject(content.toString()); JSONObject ticker = head.getJSONObject("ticker"); Double avg = ticker.getDouble("avg"); // This is bitcoins priced in euros. We want FTC! avg *= btcRate; String s_avg = String.format("%.4f", avg).replace(',', '.'); rates.put("EUR", new ExchangeRate("EUR", Utils.toNanoCoins(s_avg), URL.getHost())); } finally { if (reader != null) reader.close(); } return rates; } catch (final IOException x) { x.printStackTrace(); } catch (final JSONException x) { x.printStackTrace(); } return null; }
From source file:de.schildbach.wallet.worldcoin.ExchangeRatesProvider.java
private static Map<String, ExchangeRate> getworldcoinCharts() { final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>(); // Keep the BTC rate around for a bit Double btcRate = 0.0;/*from w w w. ja va2 s .co m*/ try { /* String currencies[] = {"USD", "BTC", "RUR"}; String urls[] = {"https://btc-e.com/api/2/ftc_btc/ticker", "https://btc-e.com/api/2/10/ticker", "https://btc-e.com/api/2/ltc_rur/ticker"}; for(int i = 0; i < currencies.length; ++i) { final String currencyCode = currencies[i]; final URL URL = new URL(urls[i]); final URLConnection connection = URL.openConnection(); connection.setConnectTimeout(TIMEOUT_MS); connection.setReadTimeout(TIMEOUT_MS); connection.connect(); final StringBuilder content = new StringBuilder(); Reader reader = null; try { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024)); IOUtils.copy(reader, content); final JSONObject head = new JSONObject(content.toString()); JSONObject ticker = head.getJSONObject("ticker"); Double avg = ticker.getDouble("avg"); String euros = String.format("%.4f", avg); // Fix things like 3,1250 euros = euros.replace(",", "."); rates.put(currencyCode, new ExchangeRate(currencyCode, Utils.toNanoCoins(euros), URL.getHost())); if(currencyCode.equalsIgnoreCase("BTC")) btcRate = avg; } finally { if (reader != null) reader.close(); } }*/ // Handle WDC/USD special since we have to do maths URL URL = null; try { URL = new URL("https://btc-e.com/api/2/ftc_btc/ticker"); } catch (MalformedURLException e) { e.printStackTrace(); } URLConnection connection = URL.openConnection(); connection.setConnectTimeout(TIMEOUT_MS); connection.setReadTimeout(TIMEOUT_MS); connection.connect(); StringBuilder content = new StringBuilder(); Reader reader = null; try { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024)); IOUtils.copy(reader, content); final JSONObject head = new JSONObject(content.toString()); JSONObject ticker = head.getJSONObject("ticker"); Double avg = ticker.getDouble("avg"); // This is worldcoins priced in bitcoins btcRate = avg; String s_avg = String.format("%.4f", avg).replace(',', '.'); rates.put("BTC", new ExchangeRate("BTC", Utils.toNanoCoins(s_avg), URL.getHost())); } finally { if (reader != null) reader.close(); } // Handle WDC/USD special since we have to do maths URL = null; URL = new URL("https://btc-e.com/api/2/btc_usd/ticker"); connection = URL.openConnection(); connection.setConnectTimeout(TIMEOUT_MS); connection.setReadTimeout(TIMEOUT_MS); connection.connect(); content = new StringBuilder(); reader = null; try { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024)); IOUtils.copy(reader, content); final JSONObject head = new JSONObject(content.toString()); JSONObject ticker = head.getJSONObject("ticker"); Double avg = ticker.getDouble("avg"); // This is bitcoins priced in dollars. We want WDC! avg *= btcRate; String s_avg = String.format("%.4f", avg).replace(',', '.'); rates.put("USD", new ExchangeRate("USD", Utils.toNanoCoins(s_avg), URL.getHost())); } finally { if (reader != null) reader.close(); } // Handle WDC/BTC special since we have to do maths URL = new URL("https://btc-e.com/api/2/btc_eur/ticker"); connection = URL.openConnection(); connection.setConnectTimeout(TIMEOUT_MS); connection.setReadTimeout(TIMEOUT_MS); connection.connect(); content = new StringBuilder(); reader = null; try { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024)); IOUtils.copy(reader, content); final JSONObject head = new JSONObject(content.toString()); JSONObject ticker = head.getJSONObject("ticker"); Double avg = ticker.getDouble("avg"); // This is bitcoins priced in euros. We want FTC! avg *= btcRate; String s_avg = String.format("%.4f", avg).replace(',', '.'); rates.put("EUR", new ExchangeRate("EUR", Utils.toNanoCoins(s_avg), URL.getHost())); } finally { if (reader != null) reader.close(); } return rates; } catch (final IOException x) { x.printStackTrace(); } catch (final JSONException x) { x.printStackTrace(); } return null; }
From source file:org.cgiar.ilri.odk.pull.backend.DataHandler.java
/** * Checks whether the server responds before the timeout. * * @param timeout The timeout in milliseconds * * @return TRUE if the server responds before the timeout *///from w w w.j a v a 2 s . c o m private static boolean isConnectedToServer(int timeout) { try { URL myUrl = new URL("http://azizi.ilri.cgiar.org"); URLConnection connection = myUrl.openConnection(); connection.setConnectTimeout(timeout); connection.connect(); return true; } catch (Exception e) { // Handle your exceptions return false; } }
From source file:org.arasthel.almeribus.utils.LoadFromWeb.java
public static int cargarParadasLinea(Context context, int numeroLinea) { if (!isConnectionEnabled(context)) { return SIN_CONEXION; }//from w w w . j a v a2 s.c om try { if (cookie == null) { if (loadCookie() == MANTENIMIENTO) { return MANTENIMIENTO; } } URL url = new URL(QUERY_ADDRESS_PARADAS_LINEA + numeroLinea); URLConnection connection = url.openConnection(); connection.setConnectTimeout(15000); connection.setReadTimeout(30000); connection.setRequestProperty("Cookie", "ASP.NET_SessionId=" + cookie); connection.setRequestProperty("REFERER", "http://m.surbus.com/tiempo-espera"); connection.setRequestProperty("Content-Type", "application/json;charset=utf-8"); connection.setRequestProperty("X-Requested-With", "XMLHttpRequest"); connection.connect(); Scanner scan = new Scanner(connection.getInputStream()); StringBuilder strBuilder = new StringBuilder(); while (scan.hasNextLine()) { strBuilder.append(scan.nextLine()); } scan.close(); JSONObject json = new JSONObject(strBuilder.toString()); Log.d("Almeribus", strBuilder.toString()); boolean isSuccessful = json.getBoolean("success"); if (isSuccessful) { DataStorage.DBHelper.eliminarParadasLinea(numeroLinea); Linea l = new Linea(numeroLinea); JSONArray list = json.getJSONArray("list"); Parada primeraParada = null; Parada paradaAnterior = null; for (int i = 0; i < list.length(); i++) { JSONObject paradaJSON = list.getJSONObject(i); int numeroParada = paradaJSON.getInt("IdBusStop"); String nombreParada = paradaJSON.getString("Name"); Parada p = null; if (DataStorage.paradas.containsKey(numeroParada)) { p = DataStorage.paradas.get(numeroParada); p.setNombre(nombreParada); } else { p = new Parada(numeroParada, nombreParada); } synchronized (DataStorage.DBHelper) { DataStorage.DBHelper.addInfoParada(numeroParada, nombreParada); } p.addLinea(l.getNumero()); if (paradaAnterior != null) { p.setAnterior(paradaAnterior.getId(), numeroLinea); } if (i == 0) { primeraParada = p; } else if (i == list.length() - 1) { primeraParada.setAnterior(p.getId(), numeroLinea); p.setSiguiente(primeraParada.getId(), numeroLinea); } if (paradaAnterior != null) { paradaAnterior.setSiguiente(p.getId(), numeroLinea); } paradaAnterior = p; synchronized (DataStorage.paradas) { if (DataStorage.paradas.containsKey(numeroParada)) { DataStorage.paradas.remove(numeroParada); } DataStorage.paradas.put(numeroParada, p); } l.addParada(p); } DataStorage.lineas.put(numeroLinea, l); for (Parada parada : l.getParadas()) { synchronized (DataStorage.DBHelper) { try { DataStorage.DBHelper.addParadaLinea(parada.getId(), numeroLinea, parada.getSiguiente(numeroLinea)); } catch (ParadaNotFoundException e) { DataStorage.DBHelper.addParadaLinea(parada.getId(), numeroLinea, 0); } } } return TODO_OK; } else { return ERROR_IO; } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { return ERROR_IO; } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ERROR_IO; }
From source file:hashengineering.digitalcoin.wallet.ExchangeRatesProvider.java
private static Object getCoinValueBTC() { Date date = new Date(); long now = date.getTime(); //final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>(); // Keep the LTC rate around for a bit Double btcRate = 0.0;//from w w w.ja v a2 s . co m String currencyCryptsy = CoinDefinition.cryptsyMarketCurrency; String urlCryptsy = "http://pubapi.cryptsy.com/api.php?method=singlemarketdata&marketid=" + CoinDefinition.cryptsyMarketId; try { // final String currencyCode = currencies[i]; final URL URLCryptsy = new URL(urlCryptsy); final URLConnection connectionCryptsy = URLCryptsy.openConnection(); connectionCryptsy.setConnectTimeout(Constants.HTTP_TIMEOUT_MS * 2); connectionCryptsy.setReadTimeout(Constants.HTTP_TIMEOUT_MS * 2); connectionCryptsy.connect(); final StringBuilder contentCryptsy = new StringBuilder(); Reader reader = null; try { reader = new InputStreamReader(new BufferedInputStream(connectionCryptsy.getInputStream(), 1024)); Io.copy(reader, contentCryptsy); final JSONObject head = new JSONObject(contentCryptsy.toString()); JSONObject returnObject = head.getJSONObject("return"); JSONObject markets = returnObject.getJSONObject("markets"); JSONObject coinInfo = markets.getJSONObject(CoinDefinition.coinTicker); JSONArray recenttrades = coinInfo.getJSONArray("recenttrades"); double btcTraded = 0.0; double coinTraded = 0.0; for (int i = 0; i < recenttrades.length(); ++i) { JSONObject trade = (JSONObject) recenttrades.get(i); btcTraded += trade.getDouble("total"); coinTraded += trade.getDouble("quantity"); } Double averageTrade = btcTraded / coinTraded; //Double lastTrade = GLD.getDouble("lasttradeprice"); //String euros = String.format("%.7f", averageTrade); // Fix things like 3,1250 //euros = euros.replace(",", "."); //rates.put(currencyCryptsy, new ExchangeRate(currencyCryptsy, Utils.toNanoCoins(euros), URLCryptsy.getHost())); if (currencyCryptsy.equalsIgnoreCase("BTC")) btcRate = averageTrade; } finally { if (reader != null) reader.close(); } return btcRate; } catch (final IOException x) { x.printStackTrace(); } catch (final JSONException x) { x.printStackTrace(); } return null; }
From source file:eu.uqasar.service.dataadapter.CubesDataService.java
/** * Check if the connection to the provided URL is possible within the provided timeout * /*www . jav a 2 s. c om*/ * @param url * @param timeout * @return True or False according to the connection success * */ private static boolean testConnectionToServer(String url, int timeout) { try { URL myUrl = new URL(url); URLConnection connection = myUrl.openConnection(); connection.setConnectTimeout(timeout); connection.connect(); return true; } catch (Exception e) { return false; } }
From source file:com.pa165.ddtroops.console.client.Application.java
/** * Delete hero from database//from www . ja va 2 s .c om * @param number hero id */ private static void deleteHero(String number) { try { URL url = new URL("http://localhost:8080/pa165/rest-jersey-server/hero/delete/" + number); URLConnection connection = url.openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/json"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); while (in.readLine() != null) { } System.out.println("Hero with id: " + number + " was deleted"); System.out.println(); in.close(); } catch (Exception e) { System.out.println("\nError when deleting hero"); System.out.println(e); } }
From source file:com.pa165.ddtroops.console.client.Application.java
/** * Delete role from database/*from ww w. j ava 2 s. com*/ * @param number role id */ private static void deleteRole(String number) { try { URL url = new URL("http://localhost:8080/pa165/rest-jersey-server/role/delete/" + number); URLConnection connection = url.openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/json"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); while (in.readLine() != null) { } System.out.println("Role with id: " + number + " was deleted"); System.out.println(); in.close(); } catch (Exception e) { System.out.println("\nError when deleting role"); System.out.println(e); } }
From source file:com.android.tools.idea.sdk.remote.internal.UrlOpener.java
private static Pair<InputStream, HttpResponse> openWithUrl(String url, Header[] inHeaders) throws IOException { URL u = new URL(url); URLConnection c = u.openConnection(); c.setConnectTimeout(sConnectionTimeoutMs); c.setReadTimeout(sSocketTimeoutMs);/*from ww w . j a v a2 s . c o m*/ if (inHeaders != null) { for (Header header : inHeaders) { c.setRequestProperty(header.getName(), header.getValue()); } } // Trigger the access to the resource // (at which point setRequestProperty can't be used anymore.) int code = 200; if (c instanceof HttpURLConnection) { code = ((HttpURLConnection) c).getResponseCode(); } // Get the input stream. That can fail for a file:// that doesn't exist // in which case we set the response code to 404. // Also we need a buffered input stream since the caller need to use is.reset(). InputStream is = null; try { is = new BufferedInputStream(c.getInputStream()); } catch (Exception ignore) { if (is == null && code == 200) { code = 404; } } HttpResponse outResponse = new BasicHttpResponse(new ProtocolVersion(u.getProtocol(), 1, 0), // make up the protocol version code, ""); //$NON-NLS-1$; Map<String, List<String>> outHeaderMap = c.getHeaderFields(); for (Entry<String, List<String>> entry : outHeaderMap.entrySet()) { String name = entry.getKey(); if (name != null) { List<String> values = entry.getValue(); if (!values.isEmpty()) { outResponse.setHeader(name, values.get(0)); } } } return Pair.of(is, outResponse); }