Example usage for java.net URLConnection getInputStream

List of usage examples for java.net URLConnection getInputStream

Introduction

In this page you can find the example usage for java.net URLConnection getInputStream.

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Returns an input stream that reads from this open connection.

Usage

From source file:com.shivam.saveServer.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//w ww . j av  a 2  s  . c  o  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
public GoogleResponse convertToLatLong(String fullAddress) throws IOException {

    /*
     * Create an java.net.URL object by passing the request URL in
     * constructor. Here you can see I am converting the fullAddress String
     * in UTF-8 format. You will get Exception if you don't convert your
     * address in UTF-8 format. Perhaps google loves UTF-8 format. :) In
     * parameter we also need to pass "sensor" parameter. sensor (required
     * parameter)  Indicates whether or not the geocoding request comes
     * from a device with a location sensor. This value must be either true
     * or false.
     */
    String URL = "http://maps.googleapis.com/maps/api/geocode/json";
    URL url = new URL(URL + "?address=" + URLEncoder.encode(fullAddress, "UTF-8") + "&sensor=false");
    // Open the Connection
    URLConnection conn = url.openConnection();

    InputStream in = conn.getInputStream();
    ObjectMapper mapper = new ObjectMapper();
    GoogleResponse response = (GoogleResponse) mapper.readValue(in, GoogleResponse.class);
    in.close();
    return response;

}

From source file:de.schildbach.wallet.goldcoin.ExchangeRatesProvider.java

private static Object getGoldCoinValueBTC_ccex() {
    Date date = new Date();
    long now = date.getTime();

    if ((now < (lastBitcoinValueCheck + 10 * 60)) && lastBitcoinValue > 0.0)
        return lastBitcoinValue;

    //final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();
    // Keep the LTC rate around for a bit
    Double btcRate = 0.0;//from   ww w  .  j  ava2  s. c o m
    String currencyCryptsy = "BTC";
    String urlCryptsy = "https://c-cex.com/t/gld-btc.json";

    try {
        // final String currencyCode = currencies[i];
        final URL URLCryptsy = new URL(urlCryptsy);
        final URLConnection connectionCryptsy = URLCryptsy.openConnection();
        connectionCryptsy.setConnectTimeout(TIMEOUT_MS * 2);
        connectionCryptsy.setReadTimeout(TIMEOUT_MS * 2);
        connectionCryptsy.connect();

        final StringBuilder contentCryptsy = new StringBuilder();

        Reader reader = null;
        try {
            reader = new InputStreamReader(new BufferedInputStream(connectionCryptsy.getInputStream(), 1024));
            IOUtils.copy(reader, contentCryptsy);
            final JSONObject head = new JSONObject(contentCryptsy.toString());

            //JSONObject returnObject = head.getJSONObject("return");
            //JSONObject markets = returnObject.getJSONObject("markets");
            JSONObject GLD = head.getJSONObject("ticker");

            //JSONArray recenttrades = GLD.getJSONArray("recenttrades");

            double btcTraded = 0.0;
            double gldTraded = 0.0;

            /*for(int i = 0; i < recenttrades.length(); ++i)
            {
            JSONObject trade = (JSONObject)recenttrades.get(i);
                    
            btcTraded += trade.getDouble("total");
            gldTraded += trade.getDouble("quantity");
                    
            }
                    
            Double averageTrade = btcTraded / gldTraded;
            */

            Double averageTrade = head.getDouble("buy");

            //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;

            lastBitcoinValue = btcRate;
            lastBitcoinValueCheck = now;
        } 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.aqnote.app.wifianalyzer.vendor.model.RemoteCall.java

@Override
protected String doInBackground(String... params) {
    if (params == null || params.length < 1 || StringUtils.isBlank(params[0])) {
        return StringUtils.EMPTY;
    }//from w  w  w .  j av a 2 s  .c  om
    String macAddress = params[0];
    String request = String.format(MAC_VENDOR_LOOKUP, macAddress);
    BufferedReader bufferedReader = null;
    try {
        URLConnection urlConnection = getURLConnection(request);
        bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            response.append(line);
        }
        String vendorName = VendorNameUtils.cleanVendorName(response.toString().trim());
        if (StringUtils.isNotBlank(vendorName)) {
            return new RemoteResult(macAddress, vendorName).toJson();
        }
        return StringUtils.EMPTY;
    } catch (Exception e) {
        return StringUtils.EMPTY;
    } finally {
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
}

From source file:edu.dfci.cccb.mev.dataset.domain.gzip.GzipTsvInput.java

@Override
public InputStream input() throws IOException {
    if (log.isDebugEnabled())
        log.debug(url);/*from  ww  w .ja va2 s  . c  o m*/

    GZIPInputStream zis = null;
    BufferedOutputStream dest = null;
    BufferedInputStream bis = null;
    File unzipped = new TemporaryFile();
    try {
        URLConnection urlc = url.openConnection();
        zis = new GZIPInputStream(urlc.getInputStream());

        int count;
        byte data[] = new byte[BUFFER];
        // write the files to the disk

        FileOutputStream fos = new FileOutputStream(unzipped);
        if (log.isDebugEnabled())
            log.debug("Unzipping SOFT file to " + unzipped.getAbsolutePath());

        dest = new BufferedOutputStream(fos, BUFFER);
        while ((count = zis.read(data, 0, BUFFER)) != -1) {
            dest.write(data, 0, count);
        }
        dest.flush();
        dest.close();
        return new FileInputStream(unzipped);

    } finally {
        if (bis != null) {
            try {
                bis.close();
            } catch (IOException ioe) {
            }
        }
        if (dest != null) {
            try {
                dest.close();
            } catch (IOException ioe) {
            }
        }
        if (zis != null) {
            try {
                zis.close();
            } catch (IOException ioe) {
            }
        }
    }

}

From source file:net.uytrewq.jogp.impl.ClientImpl.java

public OgpValues parseURL(URL url) throws IOException, HtmlException {
    URLConnection conn = null;
    InputStream is = null;// w  w  w.  j av a 2 s . c o m
    try {
        conn = url.openConnection();
        is = conn.getInputStream();
        return parse("", new InputSource(is));
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            // ignore
            logger.error("failed to close input stream", e);
        }
    }
}

From source file:com.cpp255.bookbarcode.DouBanBookInfoXmlParser.java

public Bitmap DownloadBitmap(String bitmapUrl) {
    Bitmap bitmap = null;/*from   ww  w .ja v  a2 s.  c  o m*/
    BufferedInputStream bis = null;

    try {
        URL url = new URL(bitmapUrl);
        URLConnection conn = url.openConnection();
        bis = new BufferedInputStream(conn.getInputStream());
        bitmap = BitmapFactory.decodeStream(bis);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (bis != null)
                bis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    return bitmap;
}

From source file:com.enonic.cms.core.http.HTTPService.java

public byte[] getURLAsBytes(String address, int timeoutMs, int readTimeoutMs) {
    BufferedReader reader = null;
    try {//from w ww .  j  a  v a2s .c o m
        URLConnection urlConn = setUpConnection(address, timeoutMs, readTimeoutMs);

        InputStream responseStream = urlConn.getInputStream();
        return IOUtils.toByteArray(responseStream);
    } catch (Exception e) {
        String message = "Failed to get URL: \"" + address + "\": " + e.getMessage();
        LOG.warn(message);
    } finally {
        try {
            closeReader(reader);
        } catch (IOException ioe) {
            String message = "Failed to close reader stream: \"" + address + "\": " + ioe.getMessage();
            LOG.warn(message);
        }
    }

    return null;
}

From source file:de.thecamper.android.androidtools.UpdateChecker.java

protected Boolean doInBackground(Void... params) {
    try {//from w  ww.ja  v  a  2  s . c o m
        // get the version code from a Get-Request
        URL url = new URL(versionURL);
        URLConnection con = url.openConnection();
        InputStream is = con.getInputStream();
        String encoding = con.getContentEncoding();
        encoding = encoding == null ? "UTF-8" : encoding;
        int versionNumber = Integer.parseInt(IOUtils.toString(is, encoding));

        // if it is a newer version out there return true
        if (versionNumber > context.getPackageManager().getPackageInfo(context.getPackageName(),
                0).versionCode) {
            if (buildNumberIncluded)
                appURL = appURL.replace("#", String.valueOf(versionNumber));
            return true;
        } else
            return false;

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (NumberFormatException e) {
        e.printStackTrace();
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    }

    return false;
}

From source file:XMLResourceBundleControl.java

  public ResourceBundle newBundle(String baseName, Locale locale, String format,
    ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException,
    IOException {//from  ww  w  . ja  va2  s  .  c om

  if ((baseName == null) || (locale == null) || (format == null) || (loader == null)) {
    throw new NullPointerException();
  }
  ResourceBundle bundle = null;
  if (!format.equals(XML)) {
    return null;
  }

  String bundleName = toBundleName(baseName, locale);
  String resourceName = toResourceName(bundleName, format);
  URL url = loader.getResource(resourceName);
  if (url == null) {
    return null;
  }
  URLConnection connection = url.openConnection();
  if (connection == null) {
    return null;
  }
  if (reload) {
    connection.setUseCaches(false);
  }
  InputStream stream = connection.getInputStream();
  if (stream == null) {
    return null;
  }
  BufferedInputStream bis = new BufferedInputStream(stream);
  bundle = new XMLResourceBundle(bis);
  bis.close();

  return bundle;
}

From source file:org.geomajas.plugin.wms.server.command.WmsGetFeatureInfoCommand.java

private String readUrl(URL url) throws Exception {
    URLConnection connection = url.openConnection();
    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

    StringBuilder response = new StringBuilder();
    String inputLine;//from   w w  w  .  j  av a  2  s .c  om
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    return response.toString();
}