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.joefernandez.irrduino.android.remote.HttpCommandTask.java

/** The system calls this to perform work in a worker thread and
  * delivers it the parameters given to AsyncTask.execute() */
protected String doInBackground(String... urls) {
    try {//w ww .j  a  va2s. co m
        URL commandURL = new URL(urls[0]);
        URLConnection conn = commandURL.openConnection();
        InputStream is = conn.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(50);

        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }

        /* Convert the Bytes read to a String. */
        return new String(baf.toByteArray());

    } catch (Exception e) {
        Log.d(TAG, "http request exception for: " + urls[0]);
        Log.d(TAG, "    Exception: " + e.getMessage());
    }
    return null;

}

From source file:eu.bitm.NominatimReverseGeocoding.NominatimReverseGeocodingJAPI.java

private String getJSON(String urlString) throws IOException {
    URL url = new URL(urlString);
    URLConnection conn = url.openConnection();
    InputStream is = conn.getInputStream();
    String json = IOUtils.toString(is, "UTF-8");
    is.close();/*from  w w w  .j ava 2 s .com*/
    return json;
}

From source file:com.iwgame.iwcloud.baidu.task.util.DownloadUtil.java

/**
 * url//  w w  w.  ja  v  a2  s . co m
 * @param strUrl
 *            The Url to be downloaded.
 * @param connectTimeout
 *            Connect timeout in milliseconds.
 * @param readTimeout
 *            Read timeout in milliseconds.
 * @param maxFileSize
 *            Max file size in BYTE.
 * @return The file content as byte array.
 */
public static byte[] downloadFile(String strUrl, int connectTimeout, int readTimeout, int maxFileSize)
        throws IOException {
    InputStream in = null;
    try {
        URL url = new URL(strUrl); // URL?
        URLConnection ucon = url.openConnection();
        ucon.setConnectTimeout(connectTimeout);
        ucon.setReadTimeout(readTimeout);
        ucon.connect();
        if (ucon.getContentLength() > maxFileSize) {
            String msg = "File " + strUrl + " size [" + ucon.getContentLength()
                    + "] too large, download stoped.";
            logger.error(msg);
            throw new ClientInternalException(msg);
        }
        if (ucon instanceof HttpURLConnection) {
            HttpURLConnection httpCon = (HttpURLConnection) ucon;
            if (httpCon.getResponseCode() > 399) {
                String msg = "Failed to download file " + strUrl + " server response "
                        + httpCon.getResponseMessage();
                logger.error(msg);
                throw new ClientInternalException(msg);
            }
        }
        in = ucon.getInputStream(); // ?
        byte[] byteBuf = new byte[BUFFER_SIZE];
        byte[] ret = null;
        int count, total = 0;
        // ??
        while ((count = in.read(byteBuf, total, BUFFER_SIZE - total)) > 0) {
            total += count;
            if (total + 124 >= BUFFER_SIZE)
                break;
        }
        if (total < BUFFER_SIZE - 124) {
            ret = ArrayUtils.subarray(byteBuf, 0, total);
        } else {
            ByteArrayOutputStream bos = new ByteArrayOutputStream(MATERIAL_SIZE);
            count = total;
            total = 0;
            do {
                bos.write(byteBuf, 0, count);
                total += count;
                if (total > maxFileSize) {
                    String msg = "File " + strUrl + " size exceed [" + maxFileSize + "] download stoped.";
                    logger.error(msg);
                    throw new ClientInternalException(msg);
                }
            } while ((count = in.read(byteBuf)) > 0);
            ret = bos.toByteArray();
        }
        if (ret.length < MIN_SIZE) {
            String msg = "File " + strUrl + " size [" + maxFileSize + "] too small.";
            logger.error(msg);
            throw new ClientInternalException(msg);
        }
        return ret;
    } catch (IOException e) {
        String msg = "Failed to download file " + strUrl + " msg=" + e.getMessage();
        logger.error(msg);
        throw e;
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            logger.error("Exception while close url - ", e);
            throw e;
        }
    }
}

From source file:com.QuarkLabs.BTCeClient.loaders.OrderBookLoader.java

@Override
public JSONObject loadInBackground() {
    String urlString = "https://btc-e.com/api/2/" + mPair.toLowerCase(Locale.US).replace("/", "_") + "/depth";
    String out = "";
    try {/*from   ww  w .  j av  a  2  s  .c  o m*/
        URL url = new URL(urlString);
        URLConnection connection = url.openConnection();
        InputStream stream = connection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
        String line;
        while ((line = reader.readLine()) != null) {
            out += line;
        }
        mData = new JSONObject(out);
        stream.close();
        reader.close();
    } catch (IOException | JSONException e) {
        e.printStackTrace();
    }
    return mData;
}

From source file:net.sf.zekr.engine.network.NetworkController.java

/**
 * Open a connection to a URI using application proxy or {@link Proxy#NO_PROXY no proxy}.
 * /* w w  w. j  av a  2  s . c  o m*/
 * @param uri
 * @return
 * @throws URISyntaxException
 * @throws IOException
 */
public InputStream openSteam(String uri) throws URISyntaxException, IOException {
    URL url = new URL(uri);
    URLConnection conn = url.openConnection(getProxy(uri));
    return conn.getInputStream();
}

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

private static Map<String, ExchangeRate> getBlockchainInfo() {
    try {/*from   www.  ja v  a 2 s  .  c o m*/
        //double btcRate = getGoldCoinValueBTC();

        Double btcRate = 0.0;

        Object result = getGoldCoinValueBTC();

        if (result == null)
            return null;

        else
            btcRate = (Double) result;

        final URL URL = new URL("https://blockchain.info/ticker");
        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 Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();

            //Add Bitcoin information
            rates.put("BTC", new ExchangeRate("BTC",
                    Utils.toNanoCoins(String.format("%.8f", btcRate).replace(",", ".")), "pubapi.cryptsy.com"));

            final JSONObject head = new JSONObject(content.toString());
            for (final Iterator<String> i = head.keys(); i.hasNext();) {
                final String currencyCode = i.next();
                final JSONObject o = head.getJSONObject(currencyCode);
                double gldInCurrency = o.getDouble("15m") * btcRate;
                final String rate = String.format("%.8f", gldInCurrency); //o.optString("15m", null);

                if (rate != null)
                    rates.put(currencyCode, new ExchangeRate(currencyCode,
                            Utils.toNanoCoins(rate.replace(",", ".")), URL.getHost()));
            }

            return rates;
        } finally {
            if (reader != null)
                reader.close();
        }
    } catch (final IOException x) {
        x.printStackTrace();
    } catch (final JSONException x) {
        x.printStackTrace();
    }

    return null;
}

From source file:com.beyondb.geocoding.BaiduAPI.java

public static String getPointByAddress(String address, String city) throws IOException {
    String resultPoint = "";
    try {//w w  w  .  jav a2 s.  com
        URL url = new URL("http://api.map.baidu.com/geocoder/v2/?ak=" + ak + "&output=xml&address=" + address
                + "&" + city);

        URLConnection connection = url.openConnection();
        /**
         * ??URLConnection?Web
         * URLConnection???Web???
         */
        connection.setDoOutput(true);
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "utf-8");
        //        remember to clean up
        out.flush();
        out.close();
        //        ?????

        String res;
        InputStream l_urlStream;
        l_urlStream = connection.getInputStream();
        if (l_urlStream != null) {
            BufferedReader in = new BufferedReader(new InputStreamReader(l_urlStream, "UTF-8"));
            StringBuilder sb = new StringBuilder("");
            while ((res = in.readLine()) != null) {
                sb.append(res.trim());
            }
            String str = sb.toString();
            System.out.println(str);
            Document doc = DocumentHelper.parseText(str); // XML
            Element rootElt = doc.getRootElement(); // ?
            //            System.out.println("" + rootElt.getName()); // ??
            Element resultElem = rootElt.element("result");
            if (resultElem.hasContent()) {
                Element locationElem = resultElem.element("location");
                Element latElem = locationElem.element("lat");
                //            System.out.print("lat:"+latElem.getTextTrim()+",");
                Element lngElem = locationElem.element("lng");
                //            System.out.println("lng:"+lngElem.getTextTrim());
                resultPoint = lngElem.getTextTrim() + "," + latElem.getTextTrim();
            } else {
                System.out.println("can't compute the coor");
                resultPoint = " , ";
            }
        } else {
            resultPoint = " , ";
        }

    } catch (DocumentException ex) {
        Logger.getLogger(BaiduAPI.class.getName()).log(Level.SEVERE, null, ex);
    }
    return resultPoint;
}

From source file:org.motechproject.server.osgi.RuleBundleLoader.java

@SuppressWarnings("unchecked")
@Override/*from   ww  w .  j a v a2  s.  c  om*/
public void loadBundle(Bundle bundle) throws Exception {
    Enumeration<URL> e = bundle.findEntries(ruleFolder, "*", false);
    String symbolicName = bundle.getSymbolicName();
    if (e != null) {
        while (e.hasMoreElements()) {
            URL url = e.nextElement();
            URLConnection conn = url.openConnection();
            InputStream inputStream = conn.getInputStream();
            knowledgeBaseManager.addOrUpdateRule(FilenameUtils.getName(url.getFile()), symbolicName,
                    inputStream);
            inputStream.close();
        }
    }
}

From source file:org.jrecruiter.service.GoogleMapsStaticTest.java

private void sendGetRequest() {

    // Send a GET request to the servlet
    try {/*from  w  ww  . jav  a2  s .co  m*/

        final URI url = GoogleMapsUtils.buildGoogleMapsStaticUrl(BigDecimal.TEN, BigDecimal.TEN, 10);
        final URLConnection conn = url.toURL().openConnection();

        final BufferedImage img = ImageIO.read(conn.getInputStream());

        Assert.assertNotNull(img);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.eucalyptus.cloudformation.CloudFormationService.java

private static String extractTemplateTextFromURL(String templateUrl, User user)
        throws ValidationErrorException {
    final URL url;
    try {//  w w  w  .  j  a va  2 s .  c om
        url = new URL(templateUrl);
    } catch (MalformedURLException e) {
        throw new ValidationErrorException("Invalid template url " + templateUrl);
    }
    // First try straight HTTP GET if url is in whitelist
    boolean inWhitelist = WhiteListURLMatcher.urlIsAllowed(url, URL_DOMAIN_WHITELIST);
    if (inWhitelist) {
        InputStream templateIn = null;
        try {
            final URLConnection connection = SslSetup.configureHttpsUrlConnection(url.openConnection());
            templateIn = connection.getInputStream();
            long contentLength = connection.getContentLengthLong();
            if (contentLength > Limits.REQUEST_TEMPLATE_URL_MAX_CONTENT_LENGTH_BYTES) {
                throw new ValidationErrorException("Template URL exceeds maximum byte count, "
                        + Limits.REQUEST_TEMPLATE_URL_MAX_CONTENT_LENGTH_BYTES);
            }
            final byte[] templateData = ByteStreams.toByteArray(new BoundedInputStream(templateIn,
                    Limits.REQUEST_TEMPLATE_URL_MAX_CONTENT_LENGTH_BYTES + 1));
            if (templateData.length > Limits.REQUEST_TEMPLATE_URL_MAX_CONTENT_LENGTH_BYTES) {
                throw new ValidationErrorException("Template URL exceeds maximum byte count, "
                        + Limits.REQUEST_TEMPLATE_URL_MAX_CONTENT_LENGTH_BYTES);
            }
            return new String(templateData, StandardCharsets.UTF_8);
        } catch (UnknownHostException ex) {
            throw new ValidationErrorException("Invalid template url " + templateUrl);
        } catch (SSLHandshakeException ex) {
            throw new ValidationErrorException("HTTPS connection error for " + templateUrl);
        } catch (IOException ex) {
            if (Strings.nullToEmpty(ex.getMessage()).startsWith("HTTPS hostname wrong")) {
                throw new ValidationErrorException(
                        "HTTPS connection failed hostname verification for " + templateUrl);
            }
            LOG.info("Unable to connect to whitelisted URL, trying S3 instead");
            LOG.debug(ex, ex);
        } finally {
            IO.close(templateIn);
        }
    }

    // Otherwise, assume the URL is a eucalyptus S3 url...
    String[] validHostBucketSuffixes = new String[] { "walrus", "objectstorage", "s3" };
    String[] validServicePaths = new String[] { ObjectStorageProperties.LEGACY_WALRUS_SERVICE_PATH,
            ComponentIds.lookup(ObjectStorage.class).getServicePath() };
    String[] validDomains = new String[] { DomainNames.externalSubdomain().relativize(Name.root).toString() };
    S3Helper.BucketAndKey bucketAndKey = S3Helper.getBucketAndKeyFromUrl(url, validServicePaths,
            validHostBucketSuffixes, validDomains);
    try (final EucaS3Client eucaS3Client = EucaS3ClientFactory
            .getEucaS3Client(new SecurityTokenAWSCredentialsProvider(user))) {
        if (eucaS3Client.getObjectMetadata(bucketAndKey.getBucket(), bucketAndKey.getKey())
                .getContentLength() > Limits.REQUEST_TEMPLATE_URL_MAX_CONTENT_LENGTH_BYTES) {
            throw new ValidationErrorException("Template URL exceeds maximum byte count, "
                    + Limits.REQUEST_TEMPLATE_URL_MAX_CONTENT_LENGTH_BYTES);
        }
        return eucaS3Client.getObjectContent(bucketAndKey.getBucket(), bucketAndKey.getKey(),
                (int) Limits.REQUEST_TEMPLATE_URL_MAX_CONTENT_LENGTH_BYTES);
    } catch (Exception ex) {
        LOG.debug("Error getting s3 object content: " + bucketAndKey.getBucket() + "/" + bucketAndKey.getKey());
        LOG.debug(ex, ex);
        throw new ValidationErrorException(
                "Template url is an S3 URL to a non-existent or unauthorized bucket/key.  (bucket="
                        + bucketAndKey.getBucket() + ", key=" + bucketAndKey.getKey());
    }
}