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:ar.com.zauber.common.image.impl.JREImageRetriver.java

/** @see ImageRetriver#retrive(URL) */
public final InputStream retrive(final URL url) throws IOException {
    Validate.notNull(url);//from   www  . ja v a2 s. co m

    final URLConnection uc = url.openConnection();
    if (uc instanceof HttpURLConnection) {
        final HttpURLConnection huc = (HttpURLConnection) uc;
        prepare(uc);
        huc.connect();
        final String contentType = huc.getContentType();
        if (contentType != null && contentType.length() > 0
                && !huc.getContentType().trim().startsWith("image/")) {

            throw new RuntimeException("la URL no parece apuntar a una imagen ");
        }
        if (huc.getContentLength() > maxBytes) {
            throw new RuntimeException("la imagen pesa ms de " + maxBytes);
        }
        final InputStream is = uc.getInputStream();
        return is;
    } else {
        throw new IllegalArgumentException("solo se soporta el protocolo " + " http");
    }
}

From source file:org.apache.niolex.commons.net.HTTPUtil.java

/**
 * Do the HTTP request./* w  w w.j ava  2 s.  c om*/
 *
 * @param strUrl the request URL
 * @param params the request parameters
 * @param paramCharset the charset used to send the request parameters
 * @param headers the request headers
 * @param connectTimeout the connection timeout
 * @param readTimeout the data read timeout
 * @param useGet whether do we use the HTTP GET method
 * @return the response pair; a is response header map, b is response body
 * @throws NetException
 */
public static final Pair<Map<String, List<String>>, byte[]> doHTTP(String strUrl, Map<String, String> params,
        String paramCharset, Map<String, String> headers, int connectTimeout, int readTimeout, boolean useGet)
        throws NetException {
    LOG.debug("Start HTTP {} request to [{}], C{}R{}.", useGet ? "GET" : "POST", strUrl, connectTimeout,
            readTimeout);
    InputStream in = null;
    try {
        // 1. For get, we pass parameters in URL; for post, we save it in reqBytes.
        byte[] reqBytes = null;
        if (!CollectionUtil.isEmpty(params)) {
            if (useGet) {
                strUrl = strUrl + '?' + prepareWwwFormUrlEncoded(params, paramCharset);
            } else {
                reqBytes = StringUtil.strToAsciiByte(prepareWwwFormUrlEncoded(params, paramCharset));
            }
        }
        URL url = new URL(strUrl); // We use Java URL to do the HTTP request.
        URLConnection ucon = url.openConnection();
        ucon.setConnectTimeout(connectTimeout);
        ucon.setReadTimeout(readTimeout);
        // 2. validate to Connection type.
        if (!(ucon instanceof HttpURLConnection)) {
            throw new NetException(NetException.ExCode.INVALID_URL_TYPE,
                    "The request is not in HTTP protocol.");
        }
        final HttpURLConnection httpCon = (HttpURLConnection) ucon;
        // 3. We add all the request headers.
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpCon.addRequestProperty(entry.getKey(), entry.getValue());
            }
        }
        // 4. For get or no parameter, we do not output data; for post, we pass parameters in Body.
        if (reqBytes == null) {
            httpCon.setDoOutput(false);
        } else {
            httpCon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpCon.setRequestProperty("Content-Length", Integer.toString(reqBytes.length));
            httpCon.setRequestMethod("POST");
            httpCon.setDoOutput(true);
        }
        httpCon.setDoInput(true);
        httpCon.connect();
        // 5. do output if needed.
        if (reqBytes != null) {
            StreamUtil.writeAndClose(httpCon.getOutputStream(), reqBytes);
        }
        // 6. Get the input stream.
        in = httpCon.getInputStream();
        final int contentLength = httpCon.getContentLength();
        validateHttpCode(strUrl, httpCon);
        byte[] ret = null;
        // 7. Read response byte array according to the strategy.
        if (contentLength > 0) {
            ret = commonDownload(contentLength, in);
        } else {
            ret = unusualDownload(strUrl, in, MAX_BODY_SIZE, true);
        }
        // 8. Parse the response headers.
        LOG.debug("Succeeded to execute HTTP request to [{}], response size {}.", strUrl, ret.length);
        return Pair.create(httpCon.getHeaderFields(), ret);
    } catch (NetException e) {
        LOG.info(e.getMessage());
        throw e;
    } catch (Exception e) {
        String msg = "Failed to execute HTTP request to [" + strUrl + "], msg=" + e.toString();
        LOG.warn(msg);
        throw new NetException(NetException.ExCode.IOEXCEPTION, msg, e);
    } finally {
        // Close the input stream.
        StreamUtil.closeStream(in);
    }
}

From source file:org.catnut.service.UpgradeService.java

private void download(Intent intent) throws IOException {
    String link = intent.getExtras().getString(DOWNLOAD_LINK);
    URL url = new URL(link);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    File apk = new File(getExternalCacheDir().getPath() + "/" + Uri.parse(link).getLastPathSegment());
    FileOutputStream outputStream = new FileOutputStream(apk);
    InputStream inputStream = new BufferedInputStream(connection.getInputStream());

    connection.connect();//ww  w  .  j a  va2 s .c om
    int length = connection.getContentLength();

    byte[] buffer = new byte[1024];
    int tmp;
    int count = 0;
    mBuilder.setContentTitle(getString(R.string.download_apk));
    mBuilder.setContentText(getString(R.string.downloading));
    while ((tmp = inputStream.read(buffer)) != -1) {
        count += tmp;
        outputStream.write(buffer, 0, tmp);
        mBuilder.setProgress(100, (int) ((count * 1.f / length) * 100), true);
        mNotificationManager.notify(ID, mBuilder.build());
    }
    inputStream.close();
    outputStream.close();
    connection.disconnect();

    Intent install = new Intent(Intent.ACTION_VIEW);
    install.setDataAndType(Uri.fromFile(apk), "application/vnd.android.package-archive");
    PendingIntent piInstall = PendingIntent.getActivity(this, 0, install, 0);
    mBuilder.setProgress(0, 0, false);
    mBuilder.setContentIntent(piInstall);

    mBuilder.setTicker(getString(R.string.done_download)).setContentTitle(getString(R.string.done_download))
            .setContentText(getString(R.string.click_to_upgrade));
    mNotificationManager.notify(ID, mBuilder.setDefaults(Notification.DEFAULT_ALL).build());
}

From source file:com.adaptris.core.http.JdkHttpProducer.java

private void processReply(HttpURLConnection http, AdaptrisMessage reply) throws IOException, CoreException {
    InputStream in = null;//  w  w  w . j a  v  a 2 s .  com
    OutputStream out = null;
    try {
        if (http.getContentLength() < TWO_MEG) {
            in = http.getInputStream();
            out = reply.getOutputStream();
        } else {
            out = new BufferedOutputStream(reply.getOutputStream(), FOUR_MEG);
            in = new BufferedInputStream(http.getInputStream(), FOUR_MEG);
        }
        StreamUtil.copyStream(in, out);
        if (httpHeadersAsMetadata()) {
            addReplyMetadata(http.getHeaderFields(), reply);
        }
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }
    reply.addMetadata(new MetadataElement(CoreConstants.HTTP_PRODUCER_RESPONSE_CODE,
            String.valueOf(http.getResponseCode())));
}

From source file:org.ut.biolab.medsavant.client.view.genetics.variantinfo.DownloadTask.java

public DownloadTask(String URLStr, String destPath, String notificationTitle) throws IOException {
    //do not want download tasks to be interrupted by changing subsection views, so 
    //use the class name for the task.        
    super(DownloadTask.class.getSimpleName(), notificationTitle);

    this.URLStr = URLStr;
    this.destPath = destPath;
    showResultsOnFinish(false);/*from   w w w .  j  a va  2s  . c  o m*/

    int filesize;
    String filename;

    URL url = new URL(URLStr);
    HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
    int responseCode = httpConn.getResponseCode();

    if (responseCode != HttpURLConnection.HTTP_OK) {
        throw new IOException("File " + URLStr + "unavailable from server");
    }

    String disposition = httpConn.getHeaderField("Content-Disposition");
    filesize = httpConn.getContentLength();

    if (disposition != null) {
        // extracts file name from header field
        int index = disposition.indexOf("filename=");
        if (index > 0) {
            filename = disposition.substring(index + 10, disposition.length() - 1);
        } else {
            filename = extractFileFromURL();
        }
    } else {
        // extracts file name from URL
        filename = extractFileFromURL();
    }
    this.filename = filename;
    this.filesize = filesize;
    httpConn.disconnect();
}

From source file:com.baasbox.android.HttpUrlConnectionClient.java

private HttpEntity asEntity(HttpURLConnection connection) {
    BasicHttpEntity entity = new BasicHttpEntity();
    InputStream in;/*ww  w  . j a  v a 2  s .co m*/
    try {
        in = connection.getInputStream();
    } catch (IOException e) {
        in = connection.getErrorStream();
    }
    entity.setContent(in);
    entity.setContentLength(connection.getContentLength());
    entity.setContentEncoding(connection.getContentEncoding());
    entity.setContentType(connection.getContentType());
    return entity;
}

From source file:com.adaptris.core.http.JdkHttpProducer.java

private void processErrorReply(HttpURLConnection http, AdaptrisMessage reply)
        throws IOException, CoreException {
    InputStream error = null;//from w  w w . jav  a  2s . c o  m
    OutputStream out = null;
    try {
        if (http.getContentLength() < TWO_MEG) {
            error = http.getErrorStream();
            out = reply.getOutputStream();
        } else {
            out = new BufferedOutputStream(reply.getOutputStream(), FOUR_MEG);
            error = new BufferedInputStream(http.getErrorStream(), FOUR_MEG);
        }
        StreamUtil.copyStream(error, out);
        if (httpHeadersAsMetadata()) {
            addReplyMetadata(http.getHeaderFields(), reply);
        }
    } finally {
        IOUtils.closeQuietly(error);
        IOUtils.closeQuietly(out);
    }
    reply.addMetadata(new MetadataElement(CoreConstants.HTTP_PRODUCER_RESPONSE_CODE,
            String.valueOf(http.getResponseCode())));
}

From source file:com.example.chengcheng.network.httpstacks.HttpUrlConnStack.java

/**
 * HTTP????,??//from ww w  . ja va  2  s .com
 * @param connection 
 * @return HttpEntity
 */
private HttpEntity entityFromURLConnwction(HttpURLConnection connection) {
    BasicHttpEntity entity = new BasicHttpEntity();
    InputStream inputStream = null;
    try {
        inputStream = connection.getInputStream();
    } catch (IOException e) {
        e.printStackTrace();
        inputStream = connection.getErrorStream();
    }

    // TODO : GZIP 
    entity.setContent(inputStream);
    entity.setContentLength(connection.getContentLength());
    entity.setContentEncoding(connection.getContentEncoding());
    entity.setContentType(connection.getContentType());

    return entity;
}

From source file:com.bitfable.ammocache.download.UrlImageDownloader.java

@Override
protected Bitmap download(String key, WeakReference<ImageView> imageViewRef) {
    URL url;/*from w  w  w  .  j  a v a2 s.  c  o  m*/

    try {
        url = new URL(key);
    } catch (MalformedURLException e) {
        Log.e(TAG, "url is malformed: " + key, e);
        return null;
    }

    HttpURLConnection urlConnection;
    try {
        urlConnection = (HttpURLConnection) url.openConnection();
    } catch (IOException e) {
        Log.e(TAG, "error while opening connection", e);
        return null;
    }

    Bitmap bitmap = null;
    InputStream httpStream = null;
    int contentLength;
    int bytesDownloaded = 0;
    try {
        contentLength = urlConnection.getContentLength();
        httpStream = new FlushedInputStream(urlConnection.getInputStream());
        ByteArrayBuffer baf = new ByteArrayBuffer(BYTE_ARRAY_BUFFER_INCREMENTAL_SIZE);
        byte[] buffer = new byte[BYTE_ARRAY_BUFFER_INCREMENTAL_SIZE];
        while (!isCancelled(imageViewRef)) {
            int incrementalRead = httpStream.read(buffer);
            if (incrementalRead == -1) {
                break;
            }
            bytesDownloaded += incrementalRead;
            if (contentLength > 0 || (bytesDownloaded > 0 && bytesDownloaded == contentLength)) {
                int progress = bytesDownloaded * 100 / contentLength;
                publishProgress(progress, imageViewRef);
            }
            baf.append(buffer, 0, incrementalRead);
        }

        if (isCancelled(imageViewRef))
            return null;

        bitmap = BitmapFactory.decodeByteArray(baf.toByteArray(), 0, baf.length());
    } catch (IOException e) {
        Log.e(TAG, "error creating InputStream", e);
    } finally {
        if (urlConnection != null)
            urlConnection.disconnect();
        if (httpStream != null) {
            try {
                httpStream.close();
            } catch (IOException e) {
                Log.e(TAG, "IOException while closing http stream", e);
            }
        }
    }

    return bitmap;
}

From source file:com.jug6ernaut.android.utilites.FileDownloader.java

public File downloadFile(File serverFile, File outputFile) throws IOException {
    long total = 0;
    long progress = 0;
    status = 0;//from  w  ww .ja v  a 2s  . com

    String stringURL = serverFile.getPath();

    //fix url as File removes //
    if (stringURL.startsWith("http:/") && !stringURL.startsWith("http://"))
        stringURL = stringURL.replace("http:/", "http://");
    if (stringURL.startsWith("https:/") && !stringURL.startsWith("https://"))
        stringURL = stringURL.replace("https:/", "https://");

    try {
        URL url = new URL(stringURL);
        HttpURLConnection c = (HttpURLConnection) url.openConnection();
        c.setRequestMethod("GET");
        c.setDoOutput(true);
        c.connect();

        File dir = outputFile.getParentFile();
        dir.mkdirs();

        FileOutputStream fos = new FileOutputStream(outputFile);
        total = c.getContentLength();
        startTalker(total);
        InputStream is = c.getInputStream();

        byte[] buffer = new byte[1024];
        int len1 = 0;
        while ((len1 = is.read(buffer)) != -1) {
            fos.write(buffer, 0, len1);
            progressTalker(len1);
            progress += len1;
        }
        finishTalker(progress);
        fos.close();
        is.close();
    } catch (Exception e) {
        cancelTalker(e);
        e.printStackTrace();
        status = STATUS_FAILED;
        return null;
    }

    if (total == progress)
        status = STATUS_SUCCESS;
    else
        status = STATUS_FAILED;

    return outputFile;
}