Example usage for java.net HttpURLConnection getContentLength

List of usage examples for java.net HttpURLConnection getContentLength

Introduction

In this page you can find the example usage for java.net HttpURLConnection getContentLength.

Prototype

public int getContentLength() 

Source Link

Document

Returns the value of the content-length header field.

Usage

From source file:com.eTilbudsavis.etasdk.network.impl.HttpURLNetwork.java

private static HttpEntity getEntity(HttpURLConnection connection) {
    BasicHttpEntity entity = new BasicHttpEntity();
    InputStream inputStream;/*  ww  w. j  a va 2s. com*/
    try {
        inputStream = connection.getInputStream();
    } catch (IOException ioe) {
        inputStream = connection.getErrorStream();
    }
    entity.setContent(inputStream);
    entity.setContentLength(connection.getContentLength());
    entity.setContentEncoding(connection.getContentEncoding());
    entity.setContentType(connection.getContentType());
    return entity;
}

From source file:com.quackware.handsfreemusic.Utility.java

public static String getSourceCode(URL url) {
    Object content = null;// w ww  .  jav  a2  s  .  co  m
    try {

        HttpURLConnection uc = (HttpURLConnection) url.openConnection();
        uc.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows; U; Windows NT 6.1; ru; rv:1.9.2.4) Gecko/20100513 Firefox/3.6.4");
        uc.connect();
        InputStream stream = uc.getInputStream();
        if (stream != null) {
            content = readStream(uc.getContentLength(), stream);
        } else if ((content = uc.getContent()) != null && content instanceof java.io.InputStream)
            content = readStream(uc.getContentLength(), (java.io.InputStream) content);
        uc.disconnect();

    } catch (Exception ex) {
        return null;
    }
    if (content != null && content instanceof String) {
        String html = (String) content;
        return html;
    } else {
        return null;
    }
}

From source file:savant.util.NetworkUtils.java

/**
 * Download a file in the background.  Notification events will be sent to the
 * supplied listener.//from  www.  j  a  v a 2  s  . c o  m
 *
 * @param u the HTTP URL to be downloaded
 * @param destDir destination directory for the file
 * @param fileName the destination file within <code>destDir</code>; use <code>null</code> to infer the name from the URL
 * @param monitor will receive DownloadEvents
 */
public static void downloadFile(final URL u, final File destDir, final String fileName,
        final DownloadMonitor monitor) {
    new Thread("NetworkUtils.downloadFile") {
        double totalBytes;

        @Override
        public void run() {
            try {
                HttpURLConnection httpConn = (HttpURLConnection) u.openConnection();
                totalBytes = httpConn.getContentLength();

                File destFile = new File(destDir,
                        fileName != null ? fileName : MiscUtils.getFilenameFromPath(u.getPath()));
                OutputStream out = new FileOutputStream(destFile);
                InputStream in = NetworkUtils.openStream(u);
                fireDownloadEvent(monitor, new DownloadEvent(DownloadEvent.Type.STARTED));
                byte[] buf = new byte[BUF_SIZE];
                long bytesSoFar = 0;
                int bytesRead;
                while ((bytesRead = in.read(buf)) != -1 && !monitor.isCancelled()) {
                    out.write(buf, 0, bytesRead);
                    if (totalBytes > 0.0) {
                        bytesSoFar += bytesRead;
                        monitor.handleEvent(new DownloadEvent(bytesSoFar / totalBytes));
                    }
                }
                fireDownloadEvent(monitor, new DownloadEvent(destFile));
            } catch (IOException x) {
                fireDownloadEvent(monitor, new DownloadEvent(x));
            }
        }
    }.start();
}

From source file:cn.garymb.wechatmoments.common.OkHttpStack.java

@SuppressWarnings("deprecation")
private static HttpEntity entityFromConnection(HttpURLConnection connection) {
    BasicHttpEntity entity = new BasicHttpEntity();
    InputStream inputStream;//from ww  w  .j  a  v a 2s  .  com
    try {
        inputStream = connection.getInputStream();
    } catch (IOException ioe) {
        inputStream = connection.getErrorStream();
    }
    entity.setContent(inputStream);
    entity.setContentLength(connection.getContentLength());
    entity.setContentEncoding(connection.getContentEncoding());
    entity.setContentType(connection.getContentType());
    return entity;
}

From source file:it.gulch.linuxday.android.utils.HttpUtils.java

public static InputStream get(final Context context, URL url, final String progressAction,
        final String progressExtra) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setReadTimeout(DEFAULT_TIMEOUT);
    connection.setConnectTimeout(DEFAULT_TIMEOUT);
    connection.connect();//from w ww  . j av  a 2  s .  c o m

    if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
        connection.disconnect();

        throw new IOException("Server returned response code: " + connection.getResponseCode());
    }

    final int length = connection.getContentLength();
    InputStream is = new BufferedInputStream(connection.getInputStream());
    if ((progressAction == null) || (length == -1)) {
        // No progress support
        return is;
    }

    // Broadcast the progression in percents, with a precision of 1/10 of the total file size
    return new ByteCountInputStream(is, new ByteCountInputStream.ByteCountListener() {

        private LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(context);

        @Override
        public void onNewCount(int byteCount) {
            // Cap percent to 100
            int percent = (byteCount >= length) ? 100 : byteCount * 100 / length;
            lbm.sendBroadcast(new Intent(progressAction).putExtra(progressExtra, percent));
        }
    }, length / 10);
}

From source file:com.kubeiwu.commontool.khttp.toolbox.HurlStack.java

/**
 * Initializes an {@link HttpEntity} from the given {@link HttpURLConnection}.
 * /*from   w w  w.  j  a  v  a 2  s . com*/
 * @param connection
 * @return an HttpEntity populated with data from <code>connection</code>.
 */
private static HttpEntity entityFromConnection(HttpURLConnection connection) {

    BasicHttpEntity entity = new BasicHttpEntity();
    InputStream inputStream;
    try {
        inputStream = connection.getInputStream();
    } catch (IOException ioe) {
        inputStream = connection.getErrorStream();
    }
    entity.setContent(inputStream);
    entity.setContentLength(connection.getContentLength());
    entity.setContentEncoding(connection.getContentEncoding());
    entity.setContentType(connection.getContentType());
    return entity;
}

From source file:com.android.volley.toolbox.HurlStack.java

/**
 * Initializes an {@link HttpEntity} from the given {@link HttpURLConnection}.
 * @param connection//  ww w. j  a  v  a  2  s . c o m
 * @return an HttpEntity populated with data from <code>connection</code>.
 */
private static HttpEntity entityFromConnection(HttpURLConnection connection) {
    BasicHttpEntity entity = new BasicHttpEntity();
    InputStream inputStream;
    try {
        inputStream = connection.getInputStream();
    } catch (IOException ioe) {
        inputStream = connection.getErrorStream();
    }
    entity.setContent(inputStream);
    entity.setContentLength(connection.getContentLength());
    entity.setContentEncoding(connection.getContentEncoding());
    entity.setContentType(connection.getContentType());
    return entity;
}

From source file:com.nxt.zyl.data.volley.toolbox.HurlStack.java

/**
 * Initializes an {@link org.apache.http.HttpEntity} from the given {@link java.net.HttpURLConnection}.
 * @param connection//from  w  ww. j ava 2 s  . c o m
 * @return an HttpEntity populated with data from <code>connection</code>.
 */
private static HttpEntity entityFromConnection(HttpURLConnection connection) {
    BasicHttpEntity entity = new BasicHttpEntity();
    InputStream inputStream;
    try {
        inputStream = connection.getInputStream();
    } catch (IOException ioe) {
        inputStream = connection.getErrorStream();
    }
    entity.setContent(inputStream);
    entity.setContentLength(connection.getContentLength());
    entity.setContentEncoding(connection.getContentEncoding());
    entity.setContentType(connection.getContentType());

    return entity;
}

From source file:com.heliosdecompiler.bootstrapper.Bootstrapper.java

private static HeliosData loadHelios() throws IOException {
    System.out.println("Finding Helios implementation");

    HeliosData data = new HeliosData();

    boolean needsToDownload = !IMPL_FILE.exists();
    if (!needsToDownload) {
        try (JarFile jarFile = new JarFile(IMPL_FILE)) {
            ZipEntry entry = jarFile.getEntry("META-INF/MANIFEST.MF");
            if (entry == null) {
                needsToDownload = true;/*from w ww. ja v  a 2s .c  o m*/
            } else {
                Manifest manifest = new Manifest(jarFile.getInputStream(entry));
                String ver = manifest.getMainAttributes().getValue("Implementation-Version");
                try {
                    data.buildNumber = Integer.parseInt(ver);
                    data.version = manifest.getMainAttributes().getValue("Version");
                    data.mainClass = manifest.getMainAttributes().getValue("Main-Class");
                } catch (NumberFormatException e) {
                    needsToDownload = true;
                }
            }
        } catch (IOException e) {
            needsToDownload = true;
        }
    }
    if (needsToDownload) {
        URL latestJar = new URL(LATEST_JAR);
        System.out.println("Downloading latest Helios implementation");

        FileOutputStream out = new FileOutputStream(IMPL_FILE);
        HttpURLConnection connection = (HttpURLConnection) latestJar.openConnection();
        if (connection.getResponseCode() == 200) {
            int contentLength = connection.getContentLength();
            if (contentLength > 0) {
                InputStream stream = connection.getInputStream();
                byte[] buffer = new byte[1024];
                int amnt;
                AtomicInteger total = new AtomicInteger();
                AtomicBoolean stop = new AtomicBoolean(false);

                Thread progressBar = new Thread() {
                    public void run() {
                        JPanel panel = new JPanel();
                        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

                        JLabel label = new JLabel();
                        label.setText("Downloading latest Helios build");
                        panel.add(label);

                        GridLayout layout = new GridLayout();
                        layout.setColumns(1);
                        layout.setRows(3);
                        panel.setLayout(layout);
                        JProgressBar pbar = new JProgressBar();
                        pbar.setMinimum(0);
                        pbar.setMaximum(100);
                        panel.add(pbar);

                        JTextArea textArea = new JTextArea(1, 3);
                        textArea.setOpaque(false);
                        textArea.setEditable(false);
                        textArea.setText("Downloaded 00.00MB/00.00MB");
                        panel.add(textArea);

                        JFrame frame = new JFrame();
                        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                        frame.setContentPane(panel);
                        frame.pack();
                        frame.setLocationRelativeTo(null);
                        frame.setVisible(true);

                        while (!stop.get()) {
                            SwingUtilities.invokeLater(
                                    () -> pbar.setValue((int) (100.0 * total.get() / contentLength)));

                            textArea.setText("Downloaded " + bytesToMeg(total.get()) + "MB/"
                                    + bytesToMeg(contentLength) + "MB");
                            try {
                                Thread.sleep(100);
                            } catch (InterruptedException ignored) {
                            }
                        }
                        frame.dispose();
                    }
                };
                progressBar.start();

                while ((amnt = stream.read(buffer)) != -1) {
                    out.write(buffer, 0, amnt);
                    total.addAndGet(amnt);
                }
                stop.set(true);
                return loadHelios();
            } else {
                throw new IOException("Content-Length set to " + connection.getContentLength());
            }
        } else if (connection.getResponseCode() == 404) { // Most likely bootstrapper is out of date
            throw new RuntimeException("Bootstrapper out of date!");
        } else {
            throw new IOException(connection.getResponseCode() + ": " + connection.getResponseMessage());
        }
    }

    return data;
}

From source file:com.hackerati.android.user_sdk.volley.HHurlStack.java

/**
 * Initializes an {@link HttpEntity} from the given
 * {@link HttpURLConnection}./*from  www  . j  a  v a  2 s  .co m*/
 * 
 * @param connection
 * @return an HttpEntity populated with data from <code>connection</code>.
 */
private static HttpEntity entityFromConnection(final HttpURLConnection connection) {
    final BasicHttpEntity entity = new BasicHttpEntity();
    InputStream inputStream;
    try {
        inputStream = connection.getInputStream();
    } catch (final IOException ioe) {
        inputStream = connection.getErrorStream();
    }
    entity.setContent(inputStream);
    entity.setContentLength(connection.getContentLength());
    entity.setContentEncoding(connection.getContentEncoding());
    entity.setContentType(connection.getContentType());
    return entity;
}