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.hmsoft.libcommon.gopro.GoProController.java

public CameraInfo getCameraInfo() {
    HttpURLConnection connection = getMediaConnection("videos/MISC/", "version.txt", null);
    if (connection == null)
        return null;
    try {//  w  w w .  j a v a  2s. c om
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            int cl = connection.getContentLength();
            StringBuilder builder = cl > 0 ? new StringBuilder(cl) : new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            return new CameraInfo(builder.toString());
        } finally {
            connection.disconnect();
        }
    } catch (IOException e) {
        Logger.warning(TAG, "Error getting version.txt", e);
    }
    return null;
}

From source file:edu.umn.cs.spatialHadoop.nasa.HTTPInputStream.java

private long getContentLength() throws IOException {
    if (length < 0) {
        int retries = Math.max(1, HTTPFileSystem.retries);
        HttpURLConnection localConn = null;
        while (localConn == null && retries-- > 0) {
            try {
                localConn = (HttpURLConnection) url.openConnection();
            } catch (java.net.SocketException e) {
                if (retries == 0)
                    throw e;
                LOG.info("Error accessing file '" + url + "'. Trials left: " + retries);
            } catch (java.net.UnknownHostException e) {
                if (retries == 0)
                    throw e;
                LOG.info("Error accessing file '" + url + "'. Trials left: " + retries);
            }//from  www. j a  va  2 s.c  o  m
        }
        length = localConn.getContentLength();
        localConn.disconnect();
    }
    return length;
}

From source file:at.spardat.xma.boot.transport.HTTPTransport.java

/**
 * get server output into a buffer// www.j  a  v a 2s.  c om
 *
 * @param   conn             connection to read from
 * @return  byte[]           server output
 * @throws  ServerException  content lenght errro
 * @throws  IOException      for read erros
 */
private byte[] readOutput(HttpURLConnection conn) throws IOException {
    InputStream serverOut = null;
    byte[] buffer = null;

    try {

        serverOut = conn.getInputStream();
        int len = conn.getContentLength();

        int read = 0;
        int all = 0;
        if (len > -1) {
            buffer = new byte[len];
            while (read > -1 && all < len) {
                read = serverOut.read(buffer, all, len - all);
                if (read > -1)
                    all += read;
            }
            if (read < 0) {
                throw new ServerException(
                        "Server reported contentLength " + len + " but send only " + all + " bytes of data");
            }
            return buffer;
        } else {

            // if no content length was send, use default size and grow dynamically
            List<byte[]> bufferList = null;
            final int defLen = 1024 * 8;
            int lastLength = 0;

            bufferList = new ArrayList<byte[]>();
            for (; read > -1; all += lastLength) {
                buffer = new byte[defLen];
                for (lastLength = 0; read > -1 && lastLength < defLen;) {
                    read = serverOut.read(buffer, lastLength, defLen - lastLength);
                    if (read > -1)
                        lastLength += read;
                }
                bufferList.add(buffer);
            }
            byte[] result = new byte[all];
            for (int i = 0; i < bufferList.size() - 1; i++) {
                System.arraycopy(bufferList.get(i), 0, result, i * defLen, defLen);
            }
            System.arraycopy(bufferList.get(bufferList.size() - 1), 0, result, (bufferList.size() - 1) * defLen,
                    lastLength);
            return result;
        }

    } finally {
        if (serverOut != null)
            serverOut.close();
    }
}

From source file:com.thx.bizcat.util.ImageDownloader.java

public void imageViewProcessing(String localImgUrl, String ServerImgUrl, ImageView imageView) {
    //1.Cache Memory?  ? 
    Bitmap bitmap = getBitmapFromCache(localImgUrl);

    if (bitmap == null) {

        //? ?  ?  ?
        File file = new File(localImgUrl);
        if (file.exists()) {
            Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
            if (bm != null)
                imageView.setImageBitmap(bm);
            else//from   ww  w .j av  a2  s .  c o  m
                file.delete();
        } else {
            try {
                //? ?   
                URL url = new URL(ServerImgUrl);

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

                //? : Input Stream? ? ??  ? (?    ? ? )
                InputStream is = conn.getInputStream();

                FileOutputStream fos = new FileOutputStream(localImgUrl);

                int len = conn.getContentLength();
                byte[] raster = new byte[len];

                int Read = 0;
                while (true) {
                    Read = is.read(raster);
                    if (Read <= 0) {
                        break;
                    }
                    fos.write(raster, 0, Read);
                }

                is.close();
                fos.close();
                conn.disconnect();

                //? ? 
                Bitmap bm = BitmapFactory.decodeFile(localImgUrl);
                if (bm != null)
                    imageView.setImageBitmap(bm);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    } else {
        imageView.setImageBitmap(bitmap);
    }
}

From source file:com.gokuai.yunkuandroidsdk.compat.v2.UrlTouchImageView.java

private Bitmap getOriImage(FileData data, ParamsCallBack callBack) {

    String uri = data.getUri();/*w w  w .  j  av  a 2s  .  co m*/
    String thumbBigPath = Config.getBigThumbPath(data.getFilehash());
    File file = new File(thumbBigPath);
    if (file.exists()) {
        Bitmap b = Util.decodeSampledBitmapFromFile(file);
        if (b != null) {
            return b;
        } else {
            file.delete();
        }
    } else {
        if (!file.getParentFile().isDirectory()) {
            file.getParentFile().mkdirs();
        }
    }

    HttpURLConnection urlConnection = null;
    BufferedOutputStream out = null;
    BufferedInputStream in = null;

    try {

        callBack.callBack(-1);

        FileOutputStream fos = new FileOutputStream(new File(thumbBigPath));

        final URL url = new URL(uri);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.connect();

        int totalLength = urlConnection.getContentLength();
        //mResponseCode = urlConnection.getResponseCode();
        if (totalLength == -1) {

            return null;
        }

        in = new BufferedInputStream(url.openStream(), IO_BUFFER_SIZE);
        out = new BufferedOutputStream(fos, IO_BUFFER_SIZE);

        byte[] buffer = new byte[4096];
        int length;
        long byteNow = 0;
        while ((length = in.read(buffer)) > 0) {
            fos.write(buffer, 0, length);
            byteNow += length;
            callBack.callBack((int) (((float) byteNow / (float) totalLength) * (float) 100));
        }
    } catch (final IOException e) {
        e.printStackTrace();
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        try {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (final IOException e) {
        }
    }

    file = new File(thumbBigPath);

    return !file.exists() ? null : Util.decodeSampledBitmapFromFile(file);
}

From source file:com.baracuda.piepet.nexusrelease.nexus.StageClient.java

private void drainOutput(HttpURLConnection conn) throws IOException {
    // for things like unauthorised (401) we won't have any content and getting the inputStream will
    // cause an IOException as we are in error - but there is no really way to tell this so check the
    // length instead.
    if (conn.getContentLength() > 0) {
        if (conn.getContentLength() < 1024) {
            byte[] data = new byte[conn.getConnectTimeout()];
        }/*  ww w  .ja  va 2  s . c  om*/
        if (conn.getErrorStream() != null) {
            IOUtils.skip(conn.getErrorStream(), conn.getContentLength());
        } else {
            IOUtils.skip(conn.getInputStream(), conn.getContentLength());
        }
    }
}

From source file:com.nostra13.universalimageloader.core.download.BaseImageDownloader.java

/**
 * Retrieves {@link InputStream} of image by URI (image is located in the network).
 *
 * @param imageUri Image URI/*from w ww .  j  av a 2s  .  c  om*/
 * @param extra    Auxiliary object which was passed to {@link DisplayImageOptions.Builder#extraForDownloader(Object)
 *                 DisplayImageOptions.extraForDownloader(Object)}; can be null
 * @return {@link InputStream} of image
 * @throws IOException if some I/O error occurs during network request or if no InputStream could be created for
 *                     URL.
 */
protected InputStream getStreamFromNetwork(String imageUri, Object extra) throws IOException {
    HttpURLConnection conn = createConnection(imageUri, extra);

    int redirectCount = 0;
    while (conn.getResponseCode() / 100 == 3 && redirectCount < MAX_REDIRECT_COUNT) {
        conn = createConnection(conn.getHeaderField("Location"), extra);
        redirectCount++;
    }

    InputStream imageStream;
    try {
        imageStream = conn.getInputStream();
    } catch (IOException e) {
        // Read all data to allow reuse connection (http://bit.ly/1ad35PY)
        IoUtils.readAndCloseStream(conn.getErrorStream());
        throw e;
    }
    return new ContentLengthInputStream(new BufferedInputStream(imageStream, BUFFER_SIZE),
            conn.getContentLength());
}

From source file:com.polyvi.xface.extension.advancedfiletransfer.XFileDownloader.java

/**
 * ??(?????/* w  w  w.  j a v a 2s  .  com*/
 * ??????)
 */
private void initDownloadInfo() {
    int totalSize = 0;
    if (isFirst(mUrl)) {
        HttpURLConnection connection = null;
        try {
            URL url = new URL(mUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(TIME_OUT_MILLISECOND);
            connection.setRequestMethod("GET");
            System.getProperties().setProperty("http.nonProxyHosts", url.getHost());
            //cookie?
            setCookieProperty(connection, mUrl);
            if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) {
                totalSize = connection.getContentLength();
                if (-1 != totalSize) {
                    mDownloadInfo = new XFileDownloadInfo(totalSize, 0, mUrl);
                    // ?mDownloadInfo??
                    mFileTransferRecorder.saveDownloadInfo(mDownloadInfo);
                } else {
                    XLog.e(CLASS_NAME, "cannot get totalSize");
                }
                // temp
                File file = new File(mLocalFilePath + TEMP_FILE_SUFFIX);
                if (file.exists()) {
                    file.delete();
                }
            }
        } catch (IOException e) {
            XLog.e(CLASS_NAME, e.getMessage());
        } finally {
            if (null != connection) {
                connection.disconnect();
            }
        }
    } else {
        // ?url?
        mDownloadInfo = mFileTransferRecorder.getDownloadInfo(mUrl);
        totalSize = mDownloadInfo.getTotalSize();
        mDownloadInfo.setCompleteSize(getCompleteSize(mLocalFilePath + TEMP_FILE_SUFFIX));
    }
    mBufferSize = getSingleTransferLength(totalSize);
}

From source file:cz.muni.fi.japanesedictionary.parser.ParserService.java

/**
 * Doenloads file from given URL. Creates new file or append old one.
 * //  w  w w  .j  a v  a2  s.  co m
 * @param url - to download from
 * @param outputFile File to save from URL
 * @return true if file was downloaded successfully else false
 * @throws IOException
 */
private boolean downloadFile(URL url, File outputFile) throws IOException {
    mCurrentlyDownloading = true;
    BufferedInputStream input;
    OutputStream output;

    HttpURLConnection connection;
    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty("Accept-Encoding", "identity");
    connection.connect();
    long fileLength = connection.getContentLength();
    long total = 0;

    if (outputFile.exists()) {
        if ((outputFile.lastModified() + downloadExpireTime) < System.currentTimeMillis()) {
            CompressFolder.deleteDirectory(outputFile);
            output = new FileOutputStream(outputFile.getPath());
        } else {
            output = new FileOutputStream(outputFile.getPath(), true);
            total = outputFile.length();
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("Accept-Encoding", "identity");
            connection.setRequestProperty("Range", "bytes=" + total + "-");
            connection.connect();
        }

    } else {
        output = new FileOutputStream(outputFile.getPath());
    }

    // velikost souboru
    input = new BufferedInputStream(connection.getInputStream(), 1024);

    if (fileLength == -1) {
        mBuilder.setProgress(100, 0, false).setContentTitle(getString(R.string.dictionary_download_title))
                .setContentText(getString(R.string.dictionary_download_in_progress)).setContentInfo("0%");

        mNotifyManager.notify(0, mBuilder.build());
    }

    byte data[] = new byte[1024];

    int count;
    int perc = 0;
    long lastUpdate = System.currentTimeMillis();
    try {
        while ((count = input.read(data)) != -1) {
            total += count;

            output.write(data, 0, count);
            // publishing the progress....
            if (fileLength != -1) {

                long current = System.currentTimeMillis();
                if (lastUpdate + 500 < current) {
                    int persPub = Math.round((((float) total / fileLength) * 100));
                    if (perc < persPub) {
                        lastUpdate = current;

                        mBuilder.setProgress(100, persPub, false).setContentInfo(persPub + "%");

                        mNotifyManager.notify(0, mBuilder.build());
                        perc = persPub;
                    }
                }
            }
        }
    } catch (IOException ex) {
        Log.w(LOG_TAG, "ConnectionLost: " + ex);
        closeIOStreams(input, output);
        mCurrentlyDownloading = false;
        return false;
    }
    mCurrentlyDownloading = false;
    closeIOStreams(input, output);
    return true;

}

From source file:com.gokuai.yunkuandroidsdk.compat.v2.UrlTouchImageView.java

private Bitmap getFromInternet(FileData data, ParamsCallBack callBack) {
    String urlString = data.getThumbBig();
    String thumbBigPath = Config.getBigThumbPath(data.getFilehash());

    File file = new File(thumbBigPath);
    if (file.exists()) {
        Bitmap b = Util.decodeSampledBitmapFromFile(file);
        if (b != null) {
            return b;
        } else {//  w  ww .  ja  va 2  s. co  m
            file.delete();
        }
    } else {
        if (!file.getParentFile().isDirectory()) {
            file.getParentFile().mkdirs();
        }
    }

    HttpURLConnection urlConnection = null;
    BufferedOutputStream out = null;
    BufferedInputStream in = null;

    try {

        callBack.callBack(-1);

        FileOutputStream fos = new FileOutputStream(new File(thumbBigPath));

        final URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.connect();
        int totalLength = urlConnection.getContentLength();
        if (totalLength == -1) {

            HttpClient httpclient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(urlString);
            HttpResponse response = httpclient.execute(httpGet);
            String errorStr = EntityUtils.toString(response.getEntity(), "UTF-8");

            JSONObject jsonObject = new JSONObject(errorStr);
            errorCode = jsonObject.optString("error_code");
            errorMsg = jsonObject.optString("error_msg");

            DebugFlag.log("error_msg", errorCode);
            DebugFlag.log("error_msg", errorMsg);
            return null;
        }

        in = new BufferedInputStream(url.openStream(), IO_BUFFER_SIZE);
        out = new BufferedOutputStream(fos, IO_BUFFER_SIZE);

        byte[] buffer = new byte[4096];
        int length;
        long byteNow = 0;
        while ((length = in.read(buffer)) > 0) {
            fos.write(buffer, 0, length);
            byteNow += length;
            callBack.callBack((int) (((float) byteNow / (float) totalLength) * (float) 100));
        }
    } catch (final IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        try {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (final IOException e) {
        }
    }

    file = new File(thumbBigPath);

    return !file.exists() ? null : Util.decodeSampledBitmapFromFile(file);
}