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.frostwire.gui.library.LibraryUtils.java

private static String[] processStreamUrl(String streamUrl) throws Exception {
    URL url = new URL(streamUrl);
    System.out.print(" - " + streamUrl);
    URLConnection conn = url.openConnection();
    conn.setConnectTimeout(10000);//from   w  w w  .  jav  a  2 s  .  c o  m
    conn.setRequestProperty("User-Agent", "Java");
    InputStream is = conn.getInputStream();
    BufferedReader d = null;
    if (conn.getContentEncoding() != null) {
        d = new BufferedReader(new InputStreamReader(is, conn.getContentEncoding()));
    } else {
        d = new BufferedReader(new InputStreamReader(is));
    }

    String name = null;
    String genre = null;
    String website = null;
    String type = null;
    String br = null;

    String strLine;
    int i = 0;
    while ((strLine = d.readLine()) != null && i < 10) {
        if (strLine.startsWith("icy-name:")) {
            name = clean(strLine.split(":")[1]);
        } else if (strLine.startsWith("icy-genre:")) {
            genre = clean(strLine.split(":")[1]);
        } else if (strLine.startsWith("icy-url:")) {
            website = strLine.split("icy-url:")[1].trim();
        } else if (strLine.startsWith("content-type:")) {
            String contentType = strLine.split(":")[1].trim();
            if (contentType.equals("audio/aacp")) {
                type = "AAC+";
            } else if (contentType.equals("audio/mpeg")) {
                type = "MP3";
            } else if (contentType.equals("audio/aac")) {
                type = "AAC";
            }
        } else if (strLine.startsWith("icy-br:")) {
            br = strLine.split(":")[1].trim() + " kbps";
        }
        i++;
    }

    is.close();

    return new String[] { name, streamUrl, br, type, website, genre };
}

From source file:net.ftb.util.AppUtils.java

public static String ConnectionToString(URLConnection c) {
    boolean failed = false;
    HttpURLConnection conn = (HttpURLConnection) c;
    try {//from w ww.ja  v a2s . co m
        if (conn.getErrorStream() != null) {
            return IOUtils.toString(conn.getErrorStream(), Charsets.UTF_8);
        } else if (conn.getInputStream() != null) {
            return IOUtils.toString(conn.getInputStream(), Charsets.UTF_8);
        } else {
            return null;
        }
    } catch (FileNotFoundException e) {
        // ignore this
    } catch (IOException e) {
        failed = true;
    } catch (Exception e) {
        failed = true;
        Logger.logDebug("failed", e);
    }

    if (failed) {
        try {
            return IOUtils.toString(c.getInputStream(), Charsets.UTF_8);
        } catch (Exception e) {
            Logger.logDebug("failed", e);
        }
    }

    return null;
}

From source file:net.rptools.lib.FileUtil.java

/**
 * Given a URL this method determines the content type of the URL (if possible) and then returns a Reader with the
 * appropriate character encoding./* w ww  .java 2 s . c  om*/
 * 
 * @param url
 *            the source of the data stream
 * @return String representing the data
 * @throws IOException
 */
public static Reader getURLAsReader(URL url) throws IOException {
    InputStreamReader isr = null;
    URLConnection conn = null;
    // We're assuming character here, but it could be bytes.  Perhaps we should
    // check the MIME type returned by the network server?
    conn = url.openConnection();
    if (log.isDebugEnabled()) {
        String type = URLConnection.guessContentTypeFromName(url.getPath());
        log.debug("result from guessContentTypeFromName(" + url.getPath() + ") is " + type);
        type = getContentType(conn.getInputStream());
        // Now make a guess and change 'encoding' to match the content type...
    }
    isr = new InputStreamReader(conn.getInputStream(), "UTF-8");
    return isr;
}

From source file:org.kde.necessitas.ministro.MinistroActivity.java

public static double downloadVersionXmlFile(Context c, boolean checkOnly) {
    if (!isOnline(c))
        return -1;
    try {//from   w  ww.  j  ava2 s. c  o  m
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document dom = null;
        Element root = null;
        URLConnection connection = getVersionUrl(c).openConnection();
        connection.setConnectTimeout(CONNECTION_TIMEOUT);
        connection.setReadTimeout(READ_TIMEOUT);
        dom = builder.parse(connection.getInputStream());
        root = dom.getDocumentElement();
        root.normalize();
        double version = Double.valueOf(root.getAttribute("latest"));
        if (MinistroService.instance().getVersion() >= version)
            return MinistroService.instance().getVersion();

        if (checkOnly)
            return version;
        String supportedFeatures = null;
        if (root.hasAttribute("features"))
            supportedFeatures = root.getAttribute("features");
        connection = getLibsXmlUrl(c, version + deviceSupportedFeatures(supportedFeatures)).openConnection();
        File file = new File(MinistroService.instance().getVersionXmlFile());
        file.delete();
        FileOutputStream outstream = new FileOutputStream(MinistroService.instance().getVersionXmlFile());
        InputStream instream = connection.getInputStream();
        byte[] tmp = new byte[2048];
        int downloaded;
        while ((downloaded = instream.read(tmp)) != -1)
            outstream.write(tmp, 0, downloaded);

        outstream.close();
        MinistroService.instance().refreshLibraries(false);
        return version;
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return -1;
}

From source file:de.dal33t.powerfolder.util.ConfigurationLoader.java

/**
 * Loads a pre-configuration from the URL
 *
 * @param from/*from   www.  j  a  v  a 2s .c  o  m*/
 *            the URL to load from
 * @return the loaded properties WITHOUT those in config.
 * @throws IOException
 */
private static Properties loadPreConfiguration(URL from, String un, char[] pw) throws IOException {
    Reject.ifNull(from, "URL is null");
    URLConnection con = from.openConnection();
    if (StringUtils.isNotBlank(un)) {
        String s = un + ":" + Util.toString(pw);
        LoginUtil.clear(pw);
        String base64 = "Basic " + Base64.encodeBytes(s.getBytes("UTF-8"));
        con.setRequestProperty("Authorization", base64);
    }
    con.setConnectTimeout(1000 * URL_CONNECT_TIMEOUT_SECONDS);
    con.setReadTimeout(1000 * URL_CONNECT_TIMEOUT_SECONDS);
    con.connect();
    InputStream in = con.getInputStream();
    try {
        return loadPreConfiguration(in);
    } finally {
        try {
            in.close();
        } catch (Exception e) {
        }
    }
}

From source file:com.servoy.extensions.plugins.http.HttpProvider.java

public static Pair<String, String> getPageDataOldImpl(URL url, int timeout) {
    StringBuffer sb = new StringBuffer();
    String charset = null;//  w  w  w .  j  a  v a 2 s  .co  m
    try {
        URLConnection connection = url.openConnection();
        if (timeout >= 0)
            connection.setConnectTimeout(timeout);
        InputStream is = connection.getInputStream();
        final String type = connection.getContentType();
        if (type != null) {
            final String[] parts = type.split(";");
            for (int i = 1; i < parts.length && charset == null; i++) {
                final String t = parts[i].trim();
                final int index = t.toLowerCase().indexOf("charset=");
                if (index != -1)
                    charset = t.substring(index + 8);
            }
        }
        InputStreamReader isr = null;
        if (charset != null)
            isr = new InputStreamReader(is, charset);
        else
            isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        int read = 0;
        while ((read = br.read()) != -1) {
            sb.append((char) read);
        }
        br.close();
        isr.close();
        is.close();
    } catch (Exception e) {
        Debug.error(e);
    }
    return new Pair<String, String>(sb.toString(), charset);
}

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  a  2 s  . com*/
    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:com.krawler.esp.servlets.importICSServlet.java

private static boolean getICalFileFromURL(File file, String url, boolean deleteOlderAndCreateNew)
        throws ServiceException {
    boolean success = false;
    InputStream is = null;//from  ww w  .  j a  v  a  2  s.  com
    try {
        URL u = new URL(url);
        URLConnection uc = u.openConnection();
        is = uc.getInputStream();
        if (uc.getContentType().contains("text/calendar")) {
            if (deleteOlderAndCreateNew) {
                file.delete(); // delete the file in store as it is an older one
            }
            file.createNewFile();
            FileOutputStream fop = new FileOutputStream(file);
            byte[] b = new byte[4096];
            int count = 0;
            while ((count = is.read(b)) >= 0) {
                fop.write(b, 0, count);
            }
            fop.close();
            closeInputStream(is);
            success = true;
        } else {
            closeInputStream(is);
            throw ServiceException.FAILURE("Given calendar URL is not a valid internet calendar.",
                    new Throwable(url));
        }
    } catch (MalformedURLException ex) {
        throw ServiceException.FAILURE(KWLErrorMsgs.calURLEx, ex);
    } catch (FileNotFoundException ex) {
        throw ServiceException.FAILURE(KWLErrorMsgs.calFileEx, ex);
    } catch (IOException ex) {
        closeInputStream(is);
        throw ServiceException.FAILURE(KWLErrorMsgs.calIOEx, ex);
    } catch (Exception ex) {
        closeInputStream(is);
        throw ServiceException.FAILURE(KWLErrorMsgs.calIOEx, ex);
    }
    return success;
}

From source file:sce.RESTAppMetricJob.java

public static byte[] readURL(String url) {
    try {/*w w  w. j  ava  2s.com*/
        URL u = new URL(url);
        URLConnection conn = u.openConnection();
        // look like simulating the request coming from Web browser solve 403 error
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13 (.NET CLR 3.5.30729)");
        byte[] bytes;
        try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"))) {
            String json = in.readLine();
            bytes = json.getBytes("UTF-8");
        }
        return bytes;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:org.acra.HttpUtils.java

/**
 * Send an HTTP(s) request with POST parameters.
 * /*w  ww  . j a  v  a 2s.  co m*/
 * @param parameters
 * @param url
 * @throws UnsupportedEncodingException
 * @throws IOException
 * @throws KeyManagementException
 * @throws NoSuchAlgorithmException
 */
static void doPost(Map<?, ?> parameters, URL url)
        throws UnsupportedEncodingException, IOException, KeyManagementException, NoSuchAlgorithmException {

    URLConnection cnx = getConnection(url);

    // Construct data
    StringBuilder dataBfr = new StringBuilder();
    Iterator<?> iKeys = parameters.keySet().iterator();
    while (iKeys.hasNext()) {
        if (dataBfr.length() != 0) {
            dataBfr.append('&');
        }
        String key = (String) iKeys.next();
        dataBfr.append(URLEncoder.encode(key, "UTF-8")).append('=')
                .append(URLEncoder.encode((String) parameters.get(key), "UTF-8"));
    }
    // POST data
    cnx.setDoOutput(true);

    OutputStreamWriter wr = new OutputStreamWriter(cnx.getOutputStream());
    Log.d(LOG_TAG, "Posting crash report data");
    wr.write(dataBfr.toString());
    wr.flush();
    wr.close();

    Log.d(LOG_TAG, "Reading response");
    BufferedReader rd = new BufferedReader(new InputStreamReader(cnx.getInputStream()));

    String line;
    while ((line = rd.readLine()) != null) {
        Log.d(LOG_TAG, line);
    }
    rd.close();
}