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:net.dian1.player.download.DownloadTask.java

public static Boolean downloadFile(DownloadJob job) throws IOException {

    // TODO rewrite to apache client

    PlaylistEntry mPlaylistEntry = job.getPlaylistEntry();
    String mDestination = job.getDestination();

    Music engineMusic = mPlaylistEntry.getMusic();
    String url = engineMusic.getFirstMusicNetUrl();

    if (TextUtils.isEmpty(url)) {
        engineMusic = requestMusicDetail(engineMusic.getId());
        url = engineMusic.getFirstMusicNetUrl();
        job.getPlaylistEntry().setMusic(engineMusic);
    }/*from  www . j  a  v  a  2  s.  co m*/

    //url = "http://room2.5dian1.net/??1/15.?.mp3";
    if (TextUtils.isEmpty(url)) {
        return false;
    }
    URL u = new URL(url);
    HttpURLConnection connection = (HttpURLConnection) u.openConnection();
    connection.setRequestMethod("GET");
    //c.setDoOutput(true);
    //c.setDoInput(true);
    connection.setRequestProperty("Accept", "*/*");
    connection.setRequestProperty("Content-Type", "audio/mpeg");
    connection.connect();
    job.setTotalSize(connection.getContentLength());

    Log.i(Dian1Application.TAG, "creating file");

    String path = DownloadHelper.getAbsolutePath(mPlaylistEntry, mDestination);
    String fileName = DownloadHelper.getFileName(mPlaylistEntry, job.getFormat());

    try {
        // Create multiple directory
        boolean success = (new File(path)).mkdirs();
        if (success) {
            Log.i(Dian1Application.TAG, "Directory: " + path + " created");
        }

    } catch (Exception e) {//Catch exception if any
        Log.e(Dian1Application.TAG, "Error creating folder", e);
        return false;
    }

    File outFile = new File(path, fileName);

    FileOutputStream fos = new FileOutputStream(outFile);

    InputStream in = connection.getInputStream();

    if (in == null) {
        // When InputStream is a NULL
        fos.close();
        return false;
    }

    byte[] buffer = new byte[1024];
    int lenght = 0;
    while ((lenght = in.read(buffer)) > 0) {
        fos.write(buffer, 0, lenght);
        job.setDownloadedSize(job.getDownloadedSize() + lenght);
    }
    fos.close();

    mPlaylistEntry.getMusic().getFirstMusicUrlInfo().setLocalUrl(outFile.getAbsolutePath());
    //downloadCover(job);
    return true;
}

From source file:org.apache.roller.weblogger.util.MediacastUtil.java

/**
 * Validate a Mediacast resource.//from www  .jav a2s  .  c  om
 */
public static final MediacastResource lookupResource(String url) throws MediacastException {

    if (url == null || url.trim().length() == 0) {
        return null;
    }

    MediacastResource resource = null;
    try {
        HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
        con.setRequestMethod("HEAD");
        int response = con.getResponseCode();
        String message = con.getResponseMessage();

        if (response != 200) {
            log.debug("Mediacast error " + response + ":" + message + " from url " + url);
            throw new MediacastException(BAD_RESPONSE, "weblogEdit.mediaCastResponseError");
        } else {
            String contentType = con.getContentType();
            long length = con.getContentLength();

            if (contentType == null || length == -1) {
                log.debug("Response valid, but contentType or length is invalid");
                throw new MediacastException(INCOMPLETE, "weblogEdit.mediaCastLacksContentTypeOrLength");
            }

            resource = new MediacastResource(url, contentType, length);
            log.debug("Valid mediacast resource = " + resource.toString());

        }
    } catch (MalformedURLException mfue) {
        log.debug("Malformed MediaCast url: " + url);
        throw new MediacastException(BAD_URL, "weblogEdit.mediaCastUrlMalformed", mfue);
    } catch (Exception e) {
        log.error("ERROR while checking MediaCast URL: " + url + ": " + e.getMessage());
        throw new MediacastException(CHECK_FAILED, "weblogEdit.mediaCastFailedFetchingInfo", e);
    }
    return resource;
}

From source file:com.gmobi.poponews.util.HttpHelper.java

public static int download(String url, File file) {
    HttpURLConnection connection = null;
    int length = 0;
    try {/*from  w w  w  .j a v a2  s. c  om*/
        URL httpURL = new URL(url);
        connection = (HttpURLConnection) httpURL.openConnection();
        connection.setConnectTimeout(15000);
        connection.setReadTimeout(30000);
        length = connection.getContentLength();
        FileHelper.copy(connection.getInputStream(), file);
        connection = null;

    } catch (Exception e) {
        Logger.error(e);
    }
    return length;
}

From source file:com.evilisn.DAO.CertMapper.java

public static byte[] httpGetBin(URI uri, boolean bActiveCheckUnknownHost) throws Exception

{

    InputStream is = null;//from w  ww  .  j av a 2 s.  c  om

    InputStream is_temp = null;

    try {

        if (uri == null)
            return null;

        URL url = uri.toURL();

        if (bActiveCheckUnknownHost) {

            url.getProtocol();

            String host = url.getHost();

            int port = url.getPort();

            if (port == -1)

                port = url.getDefaultPort();

            InetSocketAddress isa = new InetSocketAddress(host, port);

            if (isa.isUnresolved()) {

                //fix JNLP popup error issue

                throw new UnknownHostException("Host Unknown:" + isa.toString());

            }

        }

        HttpURLConnection uc = (HttpURLConnection) url.openConnection();

        uc.setDoInput(true);

        uc.setAllowUserInteraction(false);

        uc.setInstanceFollowRedirects(true);

        setTimeout(uc);

        String contentEncoding = uc.getContentEncoding();

        int len = uc.getContentLength();

        // is = uc.getInputStream();

        if (contentEncoding != null && contentEncoding.toLowerCase().indexOf("gzip") != -1)

        {

            is_temp = uc.getInputStream();

            is = new GZIPInputStream(is_temp);

        }

        else if (contentEncoding != null && contentEncoding.toLowerCase().indexOf("deflate") != -1)

        {

            is_temp = uc.getInputStream();

            is = new InflaterInputStream(is_temp);

        }

        else

        {

            is = uc.getInputStream();

        }

        if (len != -1) {

            int ch = 0, i = 0;

            byte[] res = new byte[len];

            while ((ch = is.read()) != -1) {

                res[i++] = (byte) (ch & 0xff);

            }

            return res;

        } else {

            ArrayList<byte[]> buffer = new ArrayList<byte[]>();

            int buf_len = 1024;

            byte[] res = new byte[buf_len];

            int ch = 0, i = 0;

            while ((ch = is.read()) != -1) {

                res[i++] = (byte) (ch & 0xff);

                if (i == buf_len) {

                    //rotate

                    buffer.add(res);

                    i = 0;

                    res = new byte[buf_len];

                }

            }

            int total_len = buffer.size() * buf_len + i;

            byte[] buf = new byte[total_len];

            for (int j = 0; j < buffer.size(); j++) {

                System.arraycopy(buffer.get(j), 0, buf, j * buf_len, buf_len);

            }

            if (i > 0) {

                System.arraycopy(res, 0, buf, buffer.size() * buf_len, i);

            }

            return buf;

        }

    } catch (Exception e) {

        e.printStackTrace();

        return null;

    } finally {

        closeInputStream(is_temp);

        closeInputStream(is);

    }

}

From source file:com.nadmm.airports.utils.NetworkUtils.java

public static boolean doHttpGet(Context context, URL url, File file, ResultReceiver receiver, Bundle result,
        Class<? extends FilterInputStream> filter) throws Exception {
    if (!NetworkUtils.isNetworkAvailable(context)) {
        return false;
    }/*from   www.  ja  v  a 2  s. c  o  m*/

    if (receiver != null && result == null) {
        throw new Exception("Result cannot be null when receiver is passed");
    }

    InputStream f = null;
    CountingInputStream in = null;
    OutputStream out = null;

    try {
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        int status = conn.getResponseCode();
        if (status != HttpURLConnection.HTTP_OK) {
            if (receiver != null) {
                // Signal the receiver that download is aborted
                result.putLong(CONTENT_LENGTH, 0);
                result.putLong(CONTENT_PROGRESS, 0);
                receiver.send(2, result);
            }
            throw new Exception(conn.getResponseMessage());
        }

        long length = conn.getContentLength();

        if (receiver != null) {
            result.putLong(CONTENT_LENGTH, length);
        }

        out = new FileOutputStream(file);
        in = new CountingInputStream(conn.getInputStream());

        if (filter != null) {
            @SuppressWarnings("unchecked")
            Constructor<FilterInputStream> ctor = (Constructor<FilterInputStream>) filter
                    .getConstructor(InputStream.class);
            f = ctor.newInstance(in);
        } else {
            f = in;
        }

        long chunk = Math.max(length / 100, 16 * 1024);
        long last = 0;

        int count;
        while ((count = f.read(sBuffer)) != -1) {
            out.write(sBuffer, 0, count);
            if (receiver != null) {
                long current = in.getCount();
                long delta = current - last;
                if (delta >= chunk) {
                    result.putLong(CONTENT_PROGRESS, current);
                    receiver.send(0, result);
                    last = current;
                }
            }
        }
        if (receiver != null) {
            // If compressed, the filter stream may not read the entire source stream
            result.putLong(CONTENT_PROGRESS, length);
            receiver.send(1, result);
        }
    } finally {
        try {
            if (f != null) {
                f.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (IOException ignored) {
        }
    }
    return true;

}

From source file:com.fastbootmobile.encore.api.common.HttpGet.java

/**
 * Downloads the data from the provided URL.
 * @param inUrl The URL to get from/* www  .java2  s. c  o m*/
 * @param query The query field. '?' + query will be appended automatically, and the query data
 *              MUST be encoded properly.
 * @return A byte array of the data
 */
public static byte[] getBytes(String inUrl, String query, boolean cached)
        throws IOException, RateLimitException {
    final String formattedUrl = inUrl + (query.isEmpty() ? "" : ("?" + query));

    Log.d(TAG, "Formatted URL: " + formattedUrl);

    URL url = new URL(formattedUrl);
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setRequestProperty("User-Agent", "OmniMusic/1.0-dev (http://www.omnirom.org)");
    urlConnection.setUseCaches(cached);
    urlConnection.setInstanceFollowRedirects(true);
    int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
    urlConnection.addRequestProperty("Cache-Control", "max-stale=" + maxStale);
    try {
        final int status = urlConnection.getResponseCode();
        // MusicBrainz returns 503 Unavailable on rate limit errors. Parse the JSON anyway.
        if (status == HttpURLConnection.HTTP_OK) {
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            int contentLength = urlConnection.getContentLength();
            if (contentLength <= 0) {
                // No length? Let's allocate 100KB.
                contentLength = 100 * 1024;
            }
            ByteArrayBuffer bab = new ByteArrayBuffer(contentLength);
            BufferedInputStream bis = new BufferedInputStream(in);
            int character;

            while ((character = bis.read()) != -1) {
                bab.append(character);
            }
            return bab.toByteArray();
        } else if (status == HttpURLConnection.HTTP_NOT_FOUND) {
            // 404
            return new byte[] {};
        } else if (status == HttpURLConnection.HTTP_FORBIDDEN) {
            return new byte[] {};
        } else if (status == HttpURLConnection.HTTP_UNAVAILABLE) {
            throw new RateLimitException();
        } else if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                || status == 307 /* HTTP/1.1 TEMPORARY REDIRECT */
                || status == HttpURLConnection.HTTP_SEE_OTHER) {
            // We've been redirected, follow the new URL
            final String followUrl = urlConnection.getHeaderField("Location");
            Log.e(TAG, "Redirected to: " + followUrl);
            return getBytes(followUrl, "", cached);
        } else {
            Log.e(TAG, "Error when fetching: " + formattedUrl + " (" + urlConnection.getResponseCode() + ")");
            return new byte[] {};
        }
    } finally {
        urlConnection.disconnect();
    }
}

From source file:org.voota.api.VootaApi.java

/**
 * Loads image data by url and returns byte array filled by this data. If
 * method fails to load image, it will return null.
 *
 * @param  urlImage          url represents image to load
 * @return                   byte array filled by image data or null if image
 *                           loading fails
 *//*from   www  .  j  a v a 2 s .  com*/
static public byte[] getUrlImageBytes(URL urlImage) {
    byte[] bytesImage = null;
    try {
        HttpURLConnection conn = (HttpURLConnection) urlImage.openConnection();
        conn.setDoInput(true);
        conn.connect();
        InputStream is = conn.getInputStream();

        int bytesAvavilable = conn.getContentLength();
        bytesImage = new byte[bytesAvavilable];
        int nReaded = 0, nSum = 0;

        while (bytesAvavilable > nSum) {
            nReaded = is.read(bytesImage, nSum, bytesAvavilable - nSum);
            nSum += nReaded;
        }
    } catch (IOException e) {
    }

    return bytesImage;
}

From source file:org.voota.api.VootaApi.java

/**
 * Loads image data by url and returns byte array filled by this data. If
 * method fails to load image, it will return null. This method takes url as
 * String object and converts file name to used character set, because it
 * may contain Spanish symbols. /* w w w  .j  a  v  a 2 s  . com*/
 *
 * @param  urlImage          url in String object represents image to load
 * @return                   byte array filled by image data or null if image
 *                           loading fails
 */
static public byte[] getUrlImageBytes(String strUrlImage) {
    byte[] bytesImage = null;
    try {
        URL urlImage = new URL(getEncodedImageUrl(strUrlImage));
        HttpURLConnection conn = (HttpURLConnection) urlImage.openConnection();
        conn.setDoInput(true);
        conn.connect();
        InputStream is = conn.getInputStream();

        int bytesAvavilable = conn.getContentLength();
        bytesImage = new byte[bytesAvavilable];
        int nReaded = 0, nSum = 0;

        while (bytesAvavilable > nSum) {
            nReaded = is.read(bytesImage, nSum, bytesAvavilable - nSum);
            nSum += nReaded;
        }
    } catch (IOException e) {
    }

    return bytesImage;
}

From source file:com.headswilllol.basiclauncher.Launcher.java

public static int getFileSize(URL url) {
    HttpURLConnection conn = null;
    try {/* w w  w  .j  a  v a2  s. c  o  m*/
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("HEAD"); // joke's on you if the server doesn't specify
        conn.getInputStream();
        return conn.getContentLength();
    } catch (Exception e) {
        return -1;
    } finally {
        if (conn != null)
            conn.disconnect();
    }
}

From source file:org.apache.hadoop.fs.azure.metrics.ResponseReceivedMetricUpdater.java

/**
 * Gets the content length of the response in the given HTTP connection.
 * @param connection The connection.//from w  w w  .  ja v  a  2s .  c o  m
 * @return The content length.
 */
private long getResponseContentLength(HttpURLConnection connection) {
    return connection.getContentLength();
}