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.wareninja.opensource.gravatar4android.common.Utils.java

public static byte[] downloadImage_alternative2(String url) throws GenericException {

    byte[] imageData = null;
    try {/* ww  w . j  a va  2s  .co  m*/

        URLConnection connection = new URL(url).openConnection();

        InputStream stream = connection.getInputStream();

        //BufferedInputStream in=new BufferedInputStream(stream);//default 8k buffer
        BufferedInputStream in = new BufferedInputStream(stream, 10240);// 10k=10240, 2x8k=16384
        ByteArrayOutputStream out = new ByteArrayOutputStream(10240);
        int read;
        byte[] b = new byte[4096];

        while ((read = in.read(b)) != -1) {
            out.write(b, 0, read);
        }

        out.flush();
        out.close();

        imageData = out.toByteArray();
    } catch (FileNotFoundException e) {
        return null;
    } catch (Exception e) {

        Log.w(TAG, "Exc=" + e);
        throw new GenericException(e);
    }

    return imageData;
}

From source file:net.sf.jabref.logic.util.Version.java

/**
 * Grabs the latest release version from the JabRef GitHub repository
 *///from w ww  .j a  va 2 s  .c om
public static Version getLatestVersion() throws IOException {
    URLConnection connection = new URL(JABREF_GITHUB_URL).openConnection();
    connection.setRequestProperty("Accept-Charset", "UTF-8");
    BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    JSONObject obj = new JSONObject(rd.readLine());
    return new Version(obj.getString("tag_name").replaceFirst("v", ""));
}

From source file:com.liveramp.cascading_ext.flow.LoggingFlow.java

private static String getTaskLogStream(URL taskLogUrl) {
    try {/*from w  w w  . j  a v a  2s . co  m*/
        URLConnection connection = taskLogUrl.openConnection();
        BufferedReader input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        try {
            StringBuilder logData = new StringBuilder();
            String line;
            while ((line = input.readLine()) != null) {
                logData.append(line).append("\n");
            }
            return logData.toString();
        } finally {
            input.close();
        }

    } catch (IOException ioe) {
        LOG.warn("Error reading task output" + ioe.getMessage());
        return "";
    }
}

From source file:bala.padio.Settings.java

public static String DownloadFromUrl(String u) {
    try {// www  . j  a  v  a  2s. co  m
        URL url = new URL(u);
        URLConnection ucon = url.openConnection();
        InputStream is = ucon.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }

        return new String(baf.toByteArray());

    } catch (Exception e) {
        Log.e(TAG, "Error: " + e);
    }
    return null;
}

From source file:com.edduarte.argus.util.PluginLoader.java

private static Class loadPlugin(Path pluginFile) throws ClassNotFoundException, IOException {

    CustomClassLoader loader = new CustomClassLoader();

    String url = "file:" + pluginFile.toAbsolutePath().toString();
    URL myUrl = new URL(url);
    URLConnection connection = myUrl.openConnection();
    InputStream input = connection.getInputStream();
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    int data = input.read();

    while (data != -1) {
        buffer.write(data);/*from w  ww  .jav a 2s .  c  o m*/
        data = input.read();
    }

    input.close();

    byte[] classData = buffer.toByteArray();
    Class loadedClass;

    try {
        loadedClass = loader.defineClass(classData);

    } catch (NoClassDefFoundError ex) {
        loadedClass = null;
    }

    loader.clearAssertionStatus();
    loader = null;
    System.gc();

    return loadedClass;
}

From source file:MainClass.java

public static void saveBinaryFile(URL u) {
    int bufferLength = 128;
    try {/*from ww  w  .j av  a 2  s.c  o m*/
        URLConnection uc = u.openConnection();
        String ct = uc.getContentType();
        int contentLength = uc.getContentLength();
        if (ct.startsWith("text/") || contentLength == -1) {
            System.err.println("This is not a binary file.");
            return;
        }

        InputStream stream = uc.getInputStream();
        byte[] buffer = new byte[contentLength];
        int bytesread = 0;
        int offset = 0;
        while (bytesread >= 0) {
            bytesread = stream.read(buffer, offset, bufferLength);
            if (bytesread == -1)
                break;
            offset += bytesread;
        }
        if (offset != contentLength) {
            System.err.println("Error: Only read " + offset + " bytes");
            System.err.println("Expected " + contentLength + " bytes");
        }

        String theFile = u.getFile();
        theFile = theFile.substring(theFile.lastIndexOf('/') + 1);
        FileOutputStream fout = new FileOutputStream(theFile);
        fout.write(buffer);
    } catch (Exception e) {
        System.err.println(e);
    }
    return;
}

From source file:Bing.java

/**
 *
 * @param query - query to use for the search
 * @return - a json array of results. each contains a title, description, url,
 * and some other metadata that can be easily extracted since its in json format
 *//*from w  ww .j a v a2 s.c  o  m*/
public static JSONArray search(String query) {
    try {
        query = "'" + query + "'";
        String encodedQuery = URLEncoder.encode(query, "UTF-8");
        System.out.println(encodedQuery);
        //            URL url = new URL("https://api.datamarket.azure.com/Bing/Search/v1/Composite?Sources=%27web%27&Query=%27car%27");
        //            URL url = new URL("http://csb.stanford.edu/class/public/pages/sykes_webdesign/05_simple.html");
        String webPage = "https://api.datamarket.azure.com/Bing/Search/v1/Composite?Sources=%27web%27&Query="
                + encodedQuery + "&$format=JSON";
        String name = "6604d12c-3e89-4859-8013-3132f78c1595";
        String password = "cefgNRl3OL4PrJJvssxkqLw0VKfYNCgyTe8wNXotUmQ";

        String authString = name + ":" + password;
        System.out.println("auth string: " + authString);
        byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
        String authStringEnc = new String(authEncBytes);
        System.out.println("Base64 encoded auth string: " + authStringEnc);

        URL url = new URL(webPage);
        URLConnection urlConnection = url.openConnection();
        urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);

        BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine).append("\n");
        }

        in.close();
        JSONParser parser = new JSONParser();
        JSONArray arr = (JSONArray) ((JSONObject) ((JSONObject) parser.parse(response.toString())).get("d"))
                .get("results");
        JSONObject obj = (JSONObject) arr.get(0);
        JSONArray out = (JSONArray) obj.get("Web");

        return out;

        //

    } catch (MalformedURLException ex) {
        Logger.getLogger(Bing.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Bing.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParseException ex) {
        Logger.getLogger(Bing.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:bala.padio.Settings.java

public static boolean DownloadFile(String httpUrl, String filePath) {
    OutputStream outputStream;/*  w ww  .  ja va  2 s .com*/
    try {
        Log.d(TAG, "Downloading url: " + httpUrl + ", to file: " + filePath);
        URL url = new URL(httpUrl);
        URLConnection ucon = url.openConnection();
        InputStream is = ucon.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);

        // file to save
        File file = new File(filePath);
        if (file.exists()) {
            file.delete();
        }
        outputStream = new BufferedOutputStream(new FileOutputStream(file));
        int current = 0;
        while ((current = bis.read()) != -1) {
            outputStream.write((byte) current);
        }
        is.close();
        outputStream.close();

        return true;
    } catch (Exception ex) {
        ex.printStackTrace();
        return false;
    }
}

From source file:Downloader.java

/**
 * Retrieves the specified page, sending the specified post data.
 * //www  .  j a v  a  2s. c  o  m
 * @param url The URL to retrieve
 * @param postData The raw POST data to send
 * @return A list of lines received from the server
 * @throws java.net.MalformedURLException If the URL is malformed
 * @throws java.io.IOException If there's an I/O error while downloading
 */
public static List<String> getPage(final String url, final String postData)
        throws MalformedURLException, IOException {

    final List<String> res = new ArrayList<String>();

    final URLConnection urlConn = getConnection(url, postData);

    final BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));

    String line;

    do {
        line = in.readLine();

        if (line != null) {
            res.add(line);
        }
    } while (line != null);

    in.close();

    return res;
}

From source file:org.ligi.android.dubwise_uavtalk.dashboard.DownloadDashboardImagesStatusAlertDialog.java

/**
 * //from w ww .  j  a v  a2 s .  c  o  m
 * @param activity
 * @param autoclose - if the alert should close when connection is established
 * 
 */
public static void show(Context activity, boolean autoclose, Intent after_connection_intent) {

    LinearLayout lin = new LinearLayout(activity);
    lin.setOrientation(LinearLayout.VERTICAL);

    ScrollView sv = new ScrollView(activity);
    TextView details_text_view = new TextView(activity);

    LinearLayout lin_in_scrollview = new LinearLayout(activity);
    lin_in_scrollview.setOrientation(LinearLayout.VERTICAL);
    sv.addView(lin_in_scrollview);
    lin_in_scrollview.addView(details_text_view);

    details_text_view.setText("no text");

    ProgressBar progress = new ProgressBar(activity, null, android.R.attr.progressBarStyleHorizontal);
    progress.setMax(img_lst.length);

    lin.addView(progress);
    lin.addView(sv);

    new AlertDialog.Builder(activity).setTitle("Download Status").setView(lin)
            .setPositiveButton("OK", new DialogDiscardingOnClickListener()).show();

    class AlertDialogUpdater implements Runnable {

        private Handler h = new Handler();
        private TextView myTextView;
        private ProgressBar myProgress;

        public AlertDialogUpdater(TextView ab, ProgressBar progress) {
            myTextView = ab;
            myProgress = progress;

        }

        public void run() {

            for (int i = 0; i < img_lst.length; i++) {
                class MsgUpdater implements Runnable {

                    private int i;

                    public MsgUpdater(int i) {
                        this.i = i;
                    }

                    public void run() {
                        myProgress.setProgress(i + 1);
                        if (i != img_lst.length - 1)
                            myTextView.setText("Downloading " + img_lst[i] + ".png");
                        else
                            myTextView.setText("Ready - please restart DUBwise to apply changes!");
                    }
                }
                h.post(new MsgUpdater(i));

                try {
                    URLConnection ucon = new URL(url_lst[i]).openConnection();
                    BufferedInputStream bis = new BufferedInputStream(ucon.getInputStream());

                    ByteArrayBuffer baf = new ByteArrayBuffer(50);
                    int current = 0;
                    while ((current = bis.read()) != -1)
                        baf.append((byte) current);

                    File path = new File(
                            Environment.getExternalStorageDirectory() + "/dubwise/images/dashboard");
                    path.mkdirs();

                    FileOutputStream fos = new FileOutputStream(
                            new File(path.getAbsolutePath() + "/" + img_lst[i] + ".png"));
                    fos.write(baf.toByteArray());
                    fos.close();
                } catch (Exception e) {
                }

                try {
                    Thread.sleep(199);
                } catch (InterruptedException e) {
                }

            }
        }
    }

    new Thread(new AlertDialogUpdater(details_text_view, progress)).start();
}