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.ris.mobile.ecloud.util.AbFileUtil.java

/**
 * ????./*from w  w  w . j  a  v  a 2  s. c o m*/
 *
 * @param Url 
 * @return int ?
 */
public static int getContentLengthFromUrl(String Url) {
    int mContentLength = 0;
    try {
        URL url = new URL(Url);
        HttpURLConnection mHttpURLConnection = (HttpURLConnection) url.openConnection();
        mHttpURLConnection.setConnectTimeout(5 * 1000);
        mHttpURLConnection.setRequestMethod("GET");
        mHttpURLConnection.setRequestProperty("Accept",
                "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
        mHttpURLConnection.setRequestProperty("Accept-Language", "zh-CN");
        mHttpURLConnection.setRequestProperty("Referer", Url);
        mHttpURLConnection.setRequestProperty("Charset", "UTF-8");
        mHttpURLConnection.setRequestProperty("User-Agent",
                "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
        mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive");
        mHttpURLConnection.connect();
        if (mHttpURLConnection.getResponseCode() == 200) {
            // ????
            mContentLength = mHttpURLConnection.getContentLength();
        }
    } catch (Exception e) {
        e.printStackTrace();
        //AbLogUtil.d(AbFileUtil.class, "?"+e.getMessage());
    }
    return mContentLength;
}

From source file:com.aniruddhc.acemusic.player.AsyncTasks.AsyncPinSongsTask.java

public void downloadSong(String songID) {

    //Update the notification.
    publishProgress(new Integer[] { 1 });

    //Check if the file already exists. If so, skip it.
    File tempFile = new File(mSaveLocation + "/" + songID + ".mp3");

    if (tempFile.exists()) {
        tempFile = null;/*from ww  w . ja v  a2s .c  om*/
        return;
    }

    tempFile = null;
    mFileName = songID + ".mp3";

    //Get the url for the song file using the songID.
    URL url = null;
    try {
        url = GMusicClientCalls.getSongStream(songID).toURL();
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return;
    } catch (JSONException e) {
        e.printStackTrace();
        return;
    } catch (URISyntaxException e) {
        e.printStackTrace();
        return;
    } catch (Exception e) {
        e.printStackTrace();
        return;
    }

    try {
        //Download the file to the specified location.
        //Create a new connection to the server.
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        //Set the request method of the connection.
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);

        //Aaaand connect!
        urlConnection.connect();

        //Set the destination path of the file.
        File SDCardRoot = new File(mSaveLocation);

        //Create the destination file.
        File file = new File(SDCardRoot, mFileName);

        //We'll use this to write the downloaded data into the file we created
        FileOutputStream fileOutput = new FileOutputStream(file);

        //Aaand we'll use this to read the data from the server.
        InputStream inputStream = urlConnection.getInputStream();

        //Total size of the file.
        fileSize = urlConnection.getContentLength();

        //Specifies how much of the total size has been downloaded.
        currentDownloadedSize = 0;

        //Buffers galore!
        byte[] buffer = new byte[1024];
        int bufferLength = 0; //Used to store a temporary size of the buffer.
        int updateValue = 0;

        //Read through the input buffer and write the destination file, piece by piece.
        while ((bufferLength = inputStream.read(buffer)) > 0) {
            fileOutput.write(buffer, 0, bufferLength);
            currentDownloadedSize += bufferLength;
            updateValue = updateValue + 1;

            //Update the notification for every 100 iterations.
            if (updateValue == 100) {
                publishProgress(new Integer[] { 0 });
                updateValue = 0;
            }

        }

        try {
            //Close the output stream.
            fileOutput.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //And we're done!
    } catch (MalformedURLException e) {
        return;
    } catch (IOException e) {
        return;
    } catch (Exception e) {
        return;
    }

    //Insert the file path of the local copy into the DB.
    ContentValues values = new ContentValues();
    String selection = DBAccessHelper.SONG_ID + "=" + "'" + songID + "'";

    String localCopyPath = null;
    try {
        localCopyPath = mContext.getCacheDir().getCanonicalPath() + "/music/" + mFileName;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    values.put(DBAccessHelper.LOCAL_COPY_PATH, localCopyPath);
    mApp.getDBAccessHelper().getWritableDatabase().update(DBAccessHelper.MUSIC_LIBRARY_TABLE, values, selection,
            null);

}

From source file:org.tightblog.service.WeblogEntryManager.java

/**
 * Create an Atom enclosure element for the resource (usually podcast or other
 * multimedia) at the specified URL.//  www. jav a  2s .com
 *
 * @param url web URL where the resource is located.
 * @return AtomEnclosure element for the resource
 */
public AtomEnclosure generateEnclosure(String url) {
    if (url == null || url.trim().length() == 0) {
        return null;
    }

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

        if (response != 200) {
            // Bad Response
            log.debug("Mediacast error {}:{} from url {}", response, message, url);
            throw new IllegalArgumentException("entryEdit.mediaCastResponseError");
        } else {
            String contentType = con.getContentType();
            long length = con.getContentLength();

            if (contentType == null || length == -1) {
                // Incomplete
                log.debug("Response valid, but contentType or length is invalid");
                throw new IllegalArgumentException("entryEdit.mediaCastLacksContentTypeOrLength");
            }

            resource = new AtomEnclosure(url, contentType, length);
            log.debug("Valid mediacast resource = {}", resource.toString());

        }
    } catch (MalformedURLException mfue) {
        // Bad URL
        log.debug("Malformed MediaCast url: {}", url);
        throw new IllegalArgumentException("entryEdit.mediaCastUrlMalformed", mfue);
    } catch (Exception e) {
        // Check Failed
        log.error("ERROR while checking MediaCast URL: {}: {}", url, e.getMessage());
        throw new IllegalArgumentException("entryEdit.mediaCastFailedFetchingInfo", e);
    }
    return resource;
}

From source file:com.bnrc.util.AbFileUtil.java

/**
 * ????./*from   w  ww  .  j  a  v  a 2 s.com*/
 *
 * @param Url ???
 * @return int ?????
 */
public static int getContentLengthFromUrl(String Url) {
    int mContentLength = 0;
    try {
        URL url = new URL(Url);
        HttpURLConnection mHttpURLConnection = (HttpURLConnection) url.openConnection();
        mHttpURLConnection.setConnectTimeout(5 * 1000);
        mHttpURLConnection.setRequestMethod("GET");
        mHttpURLConnection.setRequestProperty("Accept",
                "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
        mHttpURLConnection.setRequestProperty("Accept-Language", "zh-CN");
        mHttpURLConnection.setRequestProperty("Referer", Url);
        mHttpURLConnection.setRequestProperty("Charset", "UTF-8");
        mHttpURLConnection.setRequestProperty("User-Agent",
                "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
        mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive");
        mHttpURLConnection.connect();
        if (mHttpURLConnection.getResponseCode() == 200) {
            // ??????
            mContentLength = mHttpURLConnection.getContentLength();
        }
    } catch (Exception e) {
        e.printStackTrace();
        AbLogUtil.d(AbFileUtil.class, "" + e.getMessage());
    }
    return mContentLength;
}

From source file:com.dv.Utils.DvFileUtil.java

/**
 * ????.//from  www .j  a v  a 2s .com
 *
 * @param Url 
 * @return int ?
 */
public static int getContentLengthFormUrl(String Url) {
    int mContentLength = 0;
    try {
        URL url = new URL(Url);
        HttpURLConnection mHttpURLConnection = (HttpURLConnection) url.openConnection();
        mHttpURLConnection.setConnectTimeout(5 * 1000);
        mHttpURLConnection.setRequestMethod("GET");
        mHttpURLConnection.setRequestProperty("Accept",
                "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
        mHttpURLConnection.setRequestProperty("Accept-Language", "zh-CN");
        mHttpURLConnection.setRequestProperty("Referer", Url);
        mHttpURLConnection.setRequestProperty("Charset", "UTF-8");
        mHttpURLConnection.setRequestProperty("User-Agent",
                "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
        mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive");
        mHttpURLConnection.connect();
        if (mHttpURLConnection.getResponseCode() == 200) {
            // ????
            mContentLength = mHttpURLConnection.getContentLength();
        }
    } catch (Exception e) {
        e.printStackTrace();
        DvLogUtil.d(DvFileUtil.class, "?" + e.getMessage());
    }
    return mContentLength;
}

From source file:com.portfolio.data.attachment.XSLService.java

void RetrieveAnswer(HttpURLConnection connection, HttpServletResponse response, String referer)
        throws MalformedURLException, IOException {
    /// Receive answer
    InputStream in;//  w ww  .  j a  v  a  2  s  .co  m
    try {
        in = connection.getInputStream();
    } catch (Exception e) {
        System.out.println(e.toString());
        in = connection.getErrorStream();
    }

    String ref = null;
    if (referer != null) {
        int first = referer.indexOf('/', 7);
        int last = referer.lastIndexOf('/');
        ref = referer.substring(first, last);
    }

    response.setContentType(connection.getContentType());
    response.setStatus(connection.getResponseCode());
    response.setContentLength(connection.getContentLength());

    /// Transfer headers
    Map<String, List<String>> headers = connection.getHeaderFields();
    int size = headers.size();
    for (int i = 1; i < size; ++i) {
        String key = connection.getHeaderFieldKey(i);
        String value = connection.getHeaderField(i);
        //         response.setHeader(key, value);
        response.addHeader(key, value);
    }

    /// Deal with correct path with set cookie
    List<String> setValues = headers.get("Set-Cookie");
    if (setValues != null) {
        String setVal = setValues.get(0);
        int pathPlace = setVal.indexOf("Path=");
        if (pathPlace > 0) {
            setVal = setVal.substring(0, pathPlace + 5); // Some assumption, may break
            setVal = setVal + ref;

            response.setHeader("Set-Cookie", setVal);
        }
    }

    /// Write back data
    DataInputStream stream = new DataInputStream(in);
    byte[] buffer = new byte[1024];
    //       int size;
    ServletOutputStream out = null;
    try {
        out = response.getOutputStream();
        while ((size = stream.read(buffer, 0, buffer.length)) != -1)
            out.write(buffer, 0, size);

    } catch (Exception e) {
        System.out.println(e.toString());
        System.out.println("Writing messed up!");
    } finally {
        in.close();
        out.flush(); // close() should flush already, but Tomcat 5.5 doesn't
        out.close();
    }
}

From source file:net.technicpack.launchercore.mirror.download.Download.java

@Override
@SuppressWarnings("unused")
public void run() {
    ReadableByteChannel rbc = null;
    FileOutputStream fos = null;//from ww w.j a v  a2 s .  co m
    try {
        HttpURLConnection conn = Utils.openHttpConnection(url);
        int response = conn.getResponseCode();
        int responseFamily = response / 100;

        if (responseFamily == 3) {
            String redirUrlText = conn.getHeaderField("Location");
            if (redirUrlText != null && !redirUrlText.isEmpty()) {
                URL redirectUrl = null;
                try {
                    redirectUrl = new URL(redirUrlText);
                } catch (MalformedURLException ex) {
                    throw new DownloadException("Invalid Redirect URL: " + url, ex);
                }

                conn = Utils.openHttpConnection(redirectUrl);
                response = conn.getResponseCode();
                responseFamily = response / 100;
            }
        }

        if (responseFamily != 2) {
            throw new DownloadException("The server issued a " + response + " response code.");
        }

        InputStream in = getConnectionInputStream(conn);

        size = conn.getContentLength();
        outFile = new File(outPath);
        outFile.delete();

        rbc = Channels.newChannel(in);
        fos = new FileOutputStream(outFile);

        stateChanged();

        Thread progress = new MonitorThread(Thread.currentThread(), rbc);
        progress.start();

        fos.getChannel().transferFrom(rbc, 0, size > 0 ? size : Integer.MAX_VALUE);
        in.close();
        rbc.close();
        progress.interrupt();

        synchronized (timeoutLock) {
            if (isTimedOut) {
                return;
            }
        }

        if (size > 0) {
            if (size == outFile.length()) {
                result = Result.SUCCESS;
            }
        } else {
            result = Result.SUCCESS;
        }
    } catch (ClosedByInterruptException ex) {
        result = Result.FAILURE;
        return;
    } catch (PermissionDeniedException e) {
        exception = e;
        result = Result.PERMISSION_DENIED;
    } catch (DownloadException e) {
        exception = e;
        result = Result.FAILURE;
    } catch (Exception e) {
        exception = e;
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(fos);
        IOUtils.closeQuietly(rbc);
    }
}

From source file:cn.org.eshow.framwork.util.AbFileUtil.java

/**
 * ????.//  w ww.j a v a 2  s  . c  o m
 *
 * @param Url 
 * @return int ?
 */
public static int getContentLengthFromUrl(String Url) {
    int mContentLength = 0;
    try {
        URL url = new URL(Url);
        HttpURLConnection mHttpURLConnection = (HttpURLConnection) url.openConnection();
        mHttpURLConnection.setConnectTimeout(5 * 1000);
        mHttpURLConnection.setRequestMethod("GET");
        mHttpURLConnection.setRequestProperty("Accept",
                "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
        mHttpURLConnection.setRequestProperty("Accept-Language", "zh-CN");
        mHttpURLConnection.setRequestProperty("Referer", Url);
        mHttpURLConnection.setRequestProperty("Charset", "UTF-8");
        mHttpURLConnection.setRequestProperty("User-Agent",
                "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
        mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive");
        mHttpURLConnection.connect();
        if (mHttpURLConnection.getResponseCode() == 200) {
            // ????
            mContentLength = mHttpURLConnection.getContentLength();
        }
    } catch (Exception e) {
        e.printStackTrace();
        AbLogUtil.d(AbFileUtil.class, "?" + e.getMessage());
    }
    return mContentLength;
}

From source file:org.digitalcampus.oppia.service.CourseIntallerService.java

private boolean downloadCourseFile(String fileUrl, String shortname, Double versionID) {

    File downloadedFile = null;/*from   ww w  . java 2s .  co  m*/
    try {
        DbHelper db = new DbHelper(this);
        User u = db.getUser(prefs.getString(PrefsActivity.PREF_USER_NAME, ""));
        DatabaseManager.getInstance().closeDatabase();

        HTTPConnectionUtils client = new HTTPConnectionUtils(this);
        String downloadUrl = client.createUrlWithCredentials(fileUrl, u.getUsername(), u.getApiKey());
        String v = "0";
        try {
            v = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        URL url = new URL(downloadUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty(CoreProtocolPNames.USER_AGENT, MobileLearning.USER_AGENT + v);
        Log.d(TAG, CoreProtocolPNames.USER_AGENT + ":" + MobileLearning.USER_AGENT + v);
        connection.setDoOutput(true);
        connection.connect();
        connection.setConnectTimeout(Integer.parseInt(prefs.getString(PrefsActivity.PREF_SERVER_TIMEOUT_CONN,
                this.getString(R.string.prefServerTimeoutConnection))));
        connection.setReadTimeout(Integer.parseInt(prefs.getString(PrefsActivity.PREF_SERVER_TIMEOUT_RESP,
                this.getString(R.string.prefServerTimeoutResponse))));

        long fileLength = connection.getContentLength();
        long availableStorage = FileUtils.getAvailableStorageSize(this);

        if (fileLength >= availableStorage) {
            sendBroadcast(fileUrl, ACTION_FAILED,
                    this.getString(R.string.error_insufficient_storage_available));
            removeDownloading(fileUrl);
            return false;
        }

        String localFileName = getLocalFilename(shortname, versionID);
        downloadedFile = new File(FileUtils.getDownloadPath(this), localFileName);
        FileOutputStream f = new FileOutputStream(downloadedFile);
        InputStream in = connection.getInputStream();

        byte[] buffer = new byte[8192];
        int len1;
        long total = 0;
        int previousProgress = 0, progress;
        while ((len1 = in.read(buffer)) > 0) {
            //If received a cancel action while downloading, stop it
            if (isCancelled(fileUrl)) {
                Log.d(TAG, "Course " + localFileName + " cancelled while downloading. Deleting temp file...");
                deleteFile(downloadedFile);
                removeCancelled(fileUrl);
                removeDownloading(fileUrl);
                return false;
            }

            total += len1;
            progress = (int) ((total * 100) / fileLength);
            if ((progress > 0) && (progress > previousProgress)) {
                sendBroadcast(fileUrl, ACTION_DOWNLOAD, "" + progress);
                previousProgress = progress;
            }
            f.write(buffer, 0, len1);
        }
        f.close();

    } catch (MalformedURLException e) {
        logAndNotifyError(fileUrl, e);
        return false;
    } catch (ProtocolException e) {
        this.deleteFile(downloadedFile);
        logAndNotifyError(fileUrl, e);
        return false;
    } catch (IOException e) {
        this.deleteFile(downloadedFile);
        logAndNotifyError(fileUrl, e);
        return false;
    } catch (UserNotFoundException unfe) {
        this.deleteFile(downloadedFile);
        logAndNotifyError(fileUrl, unfe);
        return false;
    }

    Log.d(TAG, fileUrl + " succesfully downloaded");
    removeDownloading(fileUrl);
    sendBroadcast(fileUrl, ACTION_INSTALL, "0");
    return true;
}