List of usage examples for java.net URLConnection connect
public abstract void connect() throws IOException;
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 ww . j ava 2 s . c o 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:ru.codeinside.gses.webui.form.JsonForm.java
static String loadTemplate(ActivitiApp app, String ref) { try {//ww w .jav a2 s.c om URL serverUrl = app.getServerUrl(); URL url = new URL(serverUrl, ref); logger().info("fetch template " + url); URLConnection connection = url.openConnection(); connection.setDoOutput(false); connection.setDoInput(true); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); connection.setUseCaches(false); connection.connect(); return Streams.toString(connection.getInputStream()); } catch (MalformedURLException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } }
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;// w w w . j a v a 2 s. c o 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:com.dynamobi.network.DynamoNetworkUdr.java
/** * Fetches the master metadata.json file on a given repository and returns the * data as a JSONObject./*from w w w . ja v a2 s . co m*/ */ private static JSONObject downloadMetadata(String repo) throws SQLException { if (repo == null) return null; try { // Grab master metadata.json URL u = new URL(repo + "/metadata.json"); URLConnection uc = u.openConnection(); uc.setConnectTimeout(1000); // generous max-of-1-second to connect uc.setReadTimeout(1000); uc.connect(); InputStreamReader in = new InputStreamReader(uc.getInputStream()); BufferedReader buff = new BufferedReader(in); StringBuffer sb = new StringBuffer(); String line = null; do { line = buff.readLine(); if (line != null) sb.append(line); } while (line != null); String data = sb.toString(); // Parse it JSONParser parser = new JSONParser(); JSONObject ob = (JSONObject) parser.parse(data); return ob; } catch (SocketTimeoutException e) { throw new SQLException(URL_TIMEOUT); } catch (MalformedURLException e) { throw new SQLException("Bad URL."); } catch (IOException e) { throw new SQLException(URL_TIMEOUT); } catch (ParseException e) { throw new SQLException("Could not parse data from URL."); } }
From source file:org.zoumbox.mh_dla_notifier.MhDlaNotifierUtils.java
public static String loadGuilde(int guildeNumber, File filesDir) { String result = ""; if (guildeNumber > 0) { File localFile = new File(filesDir, "guildes.txt"); if (!localFile.exists()) { Log.i(TAG, "Not existing, fetching from " + "http://www.mountyhall.com/ftp/Public_Guildes.txt"); BufferedInputStream bis = null; try { URL url = new URL("http://www.mountyhall.com/ftp/Public_Guildes.txt"); URLConnection conn = url.openConnection(); conn.connect(); final BufferedInputStream fbis = new BufferedInputStream(conn.getInputStream()); bis = fbis;/* ww w. ja va2s . c o m*/ inputStreamToFile(fbis, localFile); } catch (Exception eee) { Log.e(TAG, "Exception", eee); } finally { closeQuitely(bis); } } BufferedReader reader = null; try { reader = new BufferedReader( new InputStreamReader(new FileInputStream(localFile), Charsets.ISO_8859_1)); String str; String beginsWith = guildeNumber + ";"; while ((str = reader.readLine()) != null) { if (str.startsWith(beginsWith)) { List<String> split = Lists .newArrayList(Splitter.on(";").omitEmptyStrings().trimResults().split(str)); result = split.get(1); break; } } } catch (FileNotFoundException e) { // Forget... } catch (IOException e) { // Forget } finally { closeQuitely(reader); } } return result; }
From source file:org.zoumbox.mh_dla_notifier.MhDlaNotifierUtils.java
protected static Bitmap loadRawBlason(String blasonUrl, File filesDir) { Bitmap result = null;/*from w ww .ja v a 2 s. co m*/ if (!Strings.isNullOrEmpty(blasonUrl)) { String fileName = BLASON_FILES_PREFIX + MhDlaNotifierUtils.md5(blasonUrl); File localFile = new File(filesDir, fileName); Log.i(TAG, "localFile: " + localFile); if (!localFile.exists()) { Log.i(TAG, "Not existing, fetching from " + blasonUrl); BufferedInputStream bis = null; try { URL url = new URL(blasonUrl); URLConnection conn = url.openConnection(); conn.connect(); bis = new BufferedInputStream(conn.getInputStream()); result = BitmapFactory.decodeStream(bis); } catch (Exception eee) { Log.e(TAG, "Exception", eee); } finally { closeQuitely(bis); } if (result != null) { Log.i(TAG, "Save fetched result to " + localFile); FileOutputStream fos = null; try { fos = new FileOutputStream(localFile); result.compress(Bitmap.CompressFormat.PNG, 90, fos); } catch (Exception eee) { Log.e(TAG, "Exception", eee); return null; } finally { closeQuitely(fos); } } } else { Log.i(TAG, "Existing, loading from cache"); BufferedInputStream bis = null; try { bis = new BufferedInputStream(new FileInputStream(localFile)); result = BitmapFactory.decodeStream(bis); bis.close(); } catch (Exception eee) { Log.e(TAG, "Exception", eee); } finally { closeQuitely(bis); } } } return result; }
From source file:io.bitsquare.common.util.Utilities.java
public static String readTextFileFromServer(String url, String userAgent) throws IOException { URLConnection connection = URI.create(url).toURL().openConnection(); connection.setDoOutput(true);/*from w ww .java 2 s .co m*/ connection.setUseCaches(false); connection.setConnectTimeout((int) TimeUnit.SECONDS.toMillis(10)); connection.addRequestProperty("User-Agent", userAgent); connection.connect(); try (InputStream inputStream = connection.getInputStream()) { return CharStreams.toString(new InputStreamReader(inputStream, Charsets.UTF_8)); } catch (IOException e) { e.printStackTrace(); throw e; } }
From source file:org.apache.brooklyn.util.http.HttpTool.java
/** * Connects to the given url and returns the connection. * Caller should {@code connection.getInputStream().close()} the result of this * (especially if they are making heavy use of this method). *//* w ww . j ava 2 s . c om*/ public static URLConnection connectToUrl(String u) throws Exception { final URL url = new URL(u); final AtomicReference<Exception> exception = new AtomicReference<Exception>(); // sometimes openConnection hangs, so run in background Future<URLConnection> f = executor.submit(new Callable<URLConnection>() { public URLConnection call() { try { HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } }); URLConnection connection = url.openConnection(); TrustingSslSocketFactory.configure(connection); connection.connect(); connection.getContentLength(); // Make sure the connection is made. return connection; } catch (Exception e) { exception.set(e); LOG.debug("Error connecting to url " + url + " (propagating): " + e, e); } return null; } }); try { URLConnection result = null; try { result = f.get(60, TimeUnit.SECONDS); } catch (InterruptedException e) { throw e; } catch (Exception e) { LOG.debug("Error connecting to url " + url + ", probably timed out (rethrowing): " + e); throw new IllegalStateException( "Connect to URL not complete within 60 seconds, for url " + url + ": " + e); } if (exception.get() != null) { LOG.debug("Error connecting to url " + url + ", thread caller of " + exception, new Throwable("source of rethrown error " + exception)); throw exception.get(); } else { return result; } } finally { f.cancel(true); } }
From source file:fr.gael.dhus.service.ProductService.java
private static boolean checkUrl(URL url) { Objects.requireNonNull(url, "`url` parameter must not be null"); // OData Synchronized product, DELME if (url.getPath().endsWith("$value")) { // Ignoring ... return true; }/*w w w.j a v a 2s.c o m*/ // Case of simple file try { File f = new File(url.toString()); if (f.exists()) return true; } catch (Exception e) { logger.debug("url \"" + url + "\" not formatted as a file"); } // Case of local URL try { URI local = new File(".").toURI(); URI uri = local.resolve(url.toURI()); File f = new File(uri); if (f.exists()) return true; } catch (Exception e) { logger.debug("url \"" + url + "\" not a local URL"); } // Case of remote URL try { URLConnection con = url.openConnection(); con.connect(); InputStream is = con.getInputStream(); is.close(); return true; } catch (Exception e) { logger.debug("url \"" + url + "\" not a remote URL"); } // Unrecovrable case return false; }
From source file:org.y20k.transistor.helpers.MetadataHelper.java
public static void prepareMetadata(final String mStreamUri, final Station mStation, final Context mContext) throws IOException { metaDataThread = new Thread(new Runnable() { @Override// w w w .j a va2s. co m public void run() { try { URLConnection connection = new URL(mStreamUri).openConnection(); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); connection.setRequestProperty("Icy-MetaData", "1"); connection.connect(); InputStream in = connection.getInputStream(); byte buf[] = new byte[16384]; // one second of 128kbit stream int count = 0; int total = 0; int metadataSize = 0; final int metadataOffset = connection.getHeaderFieldInt("icy-metaint", 0); int bitRate = Math.max(connection.getHeaderFieldInt("icy-br", 128), 32); LogHelper.v(LOG_TAG, "createProxyConnection: connected, icy-metaint " + metadataOffset + " icy-br " + bitRate); Thread thisThread = Thread.currentThread(); int thisThreadCounter = 0; while (true && metaDataThread == thisThread) { if (thisThreadCounter > 20) { //only try 20 times and terminate thread to be sure getting metadata LogHelper.v(LOG_TAG, "thisThreadCounter: Upper Break at thisThreadCounter=" + thisThreadCounter); break; } thisThreadCounter++; count = Math.min(in.available(), buf.length); if (count <= 0) { count = Math.min(bitRate * 64, buf.length); // buffer half-second of stream data } if (metadataOffset > 0) { count = Math.min(count, metadataOffset - total); } count = in.read(buf, 0, count); if (count == 0) { continue; } if (count < 0) { LogHelper.v(LOG_TAG, "thisThreadCounter: Break at -count < 0- thisThreadCounter=" + thisThreadCounter); break; } total += count; if (metadataOffset > 0 && total >= metadataOffset) { // read metadata total = 0; count = in.read(); if (count < 0) { LogHelper.v(LOG_TAG, "thisThreadCounter: Break2 at -count < 0- thisThreadCounter=" + thisThreadCounter); break; } count *= 16; metadataSize = count; if (metadataSize == 0) { continue; } // maximum metadata length is 4080 bytes total = 0; while (total < metadataSize) { count = in.read(buf, total, count); if (count < 0) { LogHelper.v(LOG_TAG, "thisThreadCounter: Break3 at -count < 0- thisThreadCounter=" + thisThreadCounter); break; } if (count == 0) { continue; } total += count; count = metadataSize - total; } total = 0; String[] metadata = new String(buf, 0, metadataSize, StandardCharsets.UTF_8).split(";"); for (String s : metadata) { if (s.indexOf(TransistorKeys.SHOUTCAST_STREAM_TITLE_HEADER) == 0 && s .length() >= TransistorKeys.SHOUTCAST_STREAM_TITLE_HEADER.length() + 1) { //handleMetadataString(s.substring(TransistorKeys.SHOUTCAST_STREAM_TITLE_HEADER.length(), s.length() - 1)); String metadata2 = s.substring( TransistorKeys.SHOUTCAST_STREAM_TITLE_HEADER.length(), s.length() - 1); if (metadata2 != null && metadata2.length() > 0) { // send local broadcast Intent i = new Intent(); i.setAction(TransistorKeys.ACTION_METADATA_CHANGED); i.putExtra(TransistorKeys.EXTRA_METADATA, metadata2); i.putExtra(TransistorKeys.EXTRA_STATION, mStation); LocalBroadcastManager.getInstance(mContext).sendBroadcast(i); // save metadata to shared preferences SharedPreferences settings = PreferenceManager .getDefaultSharedPreferences(mContext); SharedPreferences.Editor editor = settings.edit(); editor.putString(TransistorKeys.PREF_STATION_METADATA, metadata2); editor.apply(); //done getting the metadata LogHelper.v(LOG_TAG, "thisThreadCounter: Lower Break at thisThreadCounter=" + thisThreadCounter); break; } // break; } } } } } catch (IOException e) { e.printStackTrace(); LogHelper.e(LOG_TAG, e.getMessage()); } } }); metaDataThread.start(); }