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.polyvi.xface.extension.advancedfiletransfer.FileDownloader.java

/**
 * ??(?????/*from   www  .  j  a  v  a 2s  .c om*/
 * ??????)
 */
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 FileDownloadInfo(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:fi.hip.sicx.store.HIPStoreClient.java

/**
 * Gets a file stored in the cloud and saves to a local disk.
 * /*from   w  ww  .  ja  v a 2  s .  c  o m*/
 * @param cloudFile The file in the cloud that is to be saved.
 * @param localOutFile The saved file name.
 * @return true if file saved successfully, otherwise false
 */
@Override
public boolean getFile(String cloudFile, String localOutFile, StorageClientObserver sco) {

    boolean ok = false;
    HttpURLConnection conn = null;
    try {
        String data = URLEncoder.encode("path", "UTF-8") + "=" + URLEncoder.encode(cloudFile, "UTF-8");

        conn = getConnection("/store/fetch");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();

        if (conn.getResponseCode() == 200) {

            InputStream in = conn.getInputStream();

            long total = conn.getContentLength();
            long sent = 0;

            System.out.println("content len is " + total);

            FileOutputStream out = new FileOutputStream(localOutFile);
            byte[] buf = new byte[1024 * 64];
            int r = 0;
            while ((r = in.read(buf)) > -1) {
                out.write(buf, 0, r);
                sent += r;
                sco.progressMade((int) ((sent * 100) / total));
            }
            out.close();
            ok = true;
        }

    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }

    closeConnection(conn);
    return ok;
}

From source file:com.hmsoft.libcommon.gopro.GoProController.java

private JSONArray getMediaJSONList() {
    HttpURLConnection connection = getMediaConnection(GP_PATH, "gpMediaList", null);
    if (connection == null)
        return null;
    try {/*from  w  ww  . j av  a 2s. c  om*/
        long start = 0;
        if (DEBUG)
            start = System.currentTimeMillis();
        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);
        }
        if (DEBUG) {
            long time = System.currentTimeMillis() - start;
            Logger.debug(TAG, "GetFileList http request handled in %ds (%d)", time / 1000, time);
        }

        JSONObject json = new JSONObject(builder.toString());
        mLastMediaList = json.optJSONArray("media");
        return mLastMediaList;
    } catch (IOException e) {
        Logger.warning(TAG, "gpMediaList: Failed to get media list", e);
    } catch (JSONException e) {
        Logger.error(TAG, "gpMediaList: Failed to parse JSON", e);
    } finally {
        connection.disconnect();
    }
    return null;
}

From source file:com.mywork.framework.util.RemoteHttpUtil.java

/**
 *  JDK???//  w  w w .j av  a2 s.  c om
 */

private void fetchContentByJDKConnection(HttpServletResponse response, String contentUrl) throws IOException {

    HttpURLConnection connection = (HttpURLConnection) new URL(contentUrl).openConnection();
    // Socket
    connection.setReadTimeout(TIMEOUT_SECONDS * 1000);
    try {
        connection.connect();

        // ?
        InputStream input;
        try {
            input = connection.getInputStream();
        } catch (FileNotFoundException e) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, contentUrl + " is not found.");
            return;
        }

        // Header
        response.setContentType(connection.getContentType());
        if (connection.getContentLength() > 0) {
            response.setContentLength(connection.getContentLength());
        }

        // 
        OutputStream output = response.getOutputStream();
        try {
            // byte?InputStreamOutputStream, ?4k.
            IOUtils.copy(input, output);
            output.flush();
        } finally {
            // ??InputStream.
            IOUtils.closeQuietly(input);
        }
    } finally {
        connection.disconnect();
    }
}

From source file:it.baywaylabs.jumpersumo.robot.ServerPolling.java

/**
 * This method is called when invoke <b>execute()</b>.<br />
 * Do not invoke manually. Use: new ServerPolling().execute(url1, url2, url3);
 *
 * @param sUrl List of Url that will be download.
 * @return null if all is going ok./*from  ww  w .  j a  v  a 2s  .c  om*/
 */
@Override
protected String doInBackground(String... sUrl) {

    InputStream input = null;
    OutputStream output = null;
    File folder = new File(Constants.DIR_ROBOT);
    String baseName = FilenameUtils.getBaseName(sUrl[0]);
    String extension = FilenameUtils.getExtension(sUrl[0]);
    Log.d(TAG, "FileName: " + baseName + " - FileExt: " + extension);

    if (!folder.exists()) {
        folder.mkdir();
    }
    HttpURLConnection connection = null;
    if (!f.isUrl(sUrl[0]))
        return "Url malformed!";
    try {
        URL url = new URL(sUrl[0]);
        connection = (HttpURLConnection) url.openConnection();
        connection.connect();

        // expect HTTP 200 OK, so we don't mistakenly save error report
        // instead of the file
        if (!sUrl[0].endsWith(".csv") && connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return "Server returned HTTP " + connection.getResponseCode() + " "
                    + connection.getResponseMessage();
        }

        // this will be useful to display download percentage
        // might be -1: server did not report the length
        int fileLength = connection.getContentLength();

        // download the file
        input = connection.getInputStream();
        output = new FileOutputStream(folder.getAbsolutePath() + "/" + baseName + "." + extension);

        byte data[] = new byte[4096];
        long total = 0;
        int count;
        while ((count = input.read(data)) != -1) {
            // allow canceling with back button
            if (isCancelled()) {
                input.close();
                return null;
            }
            total += count;
            // publishing the progress....
            if (fileLength > 0) // only if total length is known
                publishProgress((int) (total * 100 / fileLength));
            output.write(data, 0, count);
        }
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
        return e.toString();
    } finally {
        try {
            if (output != null)
                output.close();
            if (input != null)
                input.close();
        } catch (IOException ignored) {
        }

        if (connection != null)
            connection.disconnect();
    }
    return null;
}

From source file:org.apache.clerezza.integrationtest.web.performance.GetRdf.java

@Override
public void run() {

    try {// ww w.  j ava 2s.c  o  m
        URL url = new URL(resourceUri);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        try {
            con.setRequestMethod("GET");
            con.setRequestProperty("Accept", "application/rdf+xml");
            con.setRequestProperty("Authorization", "Basic " + authString);
            con.setDoInput(true);

            int responseCode = con.getResponseCode();
            if (responseCode != 200) {
                throw new RuntimeException("GetRdf: (GET) unexpected " + "response code: " + responseCode);
            }

            String contentType = con.getContentType();
            if (contentType == null) {
                throw new RuntimeException("GetRdf: Couldn't determine content type.");
            }

            int length = con.getContentLength();
            byte[] content = new byte[length];
            InputStream inputStream = con.getInputStream();
            try {

                int i = 0;
                while (i < length && ((content[i++] = (byte) inputStream.read()) != -1)) {
                }
                if (i != length) {
                    throw new RuntimeException("GetRdf: Couldn't read all data.");
                }
                String contentStr = new String(content, getCharSet(contentType));

                if (!contentStr.contains(getInfoBitString(rdfResource))) {
                    throw new RuntimeException("GetRdf: Content does not contain expected information.");
                }
            } finally {
                inputStream.close();
            }
        } finally {
            con.disconnect();
        }
    } catch (MalformedURLException me) {
        me.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
}

From source file:org.apache.clerezza.integrationtest.web.performance.GetSparqlQuery.java

@Override
public void run() {
    try {//from   w w w  . j  a v a 2s .  c  o  m
        String queryParams = URLEncoder.encode("query", UTF8) + "=" + URLEncoder.encode(query, UTF8);
        queryParams += "&";
        queryParams += URLEncoder.encode("default-graph-uri", UTF8) + "="
                + URLEncoder.encode("urn:x-localinstance:/content.graph", UTF8);
        URL url = new URL(requestUri + "?" + queryParams);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        try {
            con.setRequestMethod("GET");
            con.setRequestProperty("Accept", "application/rdf+xml");
            con.setRequestProperty("Authorization",
                    "Basic " + new String(Base64.encodeBase64((username + ":" + password).getBytes())));
            con.setDoOutput(true);

            int responseCode = con.getResponseCode();
            if (responseCode != 200) {
                throw new RuntimeException("GetSparqlQuery: unexpected " + "response code: " + responseCode);
            }
            String contentType = con.getContentType();
            if (contentType == null) {
                throw new RuntimeException("GetSparqlQuery: Couldn't determine content type.");
            }
            int length = con.getContentLength();
            byte[] content = new byte[length];
            InputStream inputStream = con.getInputStream();
            try {
                int i = 0;
                while (i < length && ((content[i++] = (byte) inputStream.read()) != -1)) {
                }
                if (i != length) {
                    throw new RuntimeException("GetSparqlQuery: Couldn't read all data.");
                }
            } finally {
                inputStream.close();
            }
        } finally {
            con.disconnect();
        }
    } catch (MalformedURLException me) {
        me.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
}

From source file:guru.benson.pinch.Pinch.java

/**
 * Read the content length for the ZIP file.
 *
 * @return The content length in bytes or -1 failed.
 *///from  w  w  w .j a  v  a2  s .  c  om
private int getHttpFileSize() {
    HttpURLConnection conn = null;
    int length = -1;
    try {
        conn = openConnection();
        conn.setRequestMethod(HttpHead.METHOD_NAME);
        conn.connect();

        // handle re-directs
        if (conn.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP) {
            if (setUrl(conn.getHeaderField("Location"))) {
                disconnect(conn);
                length = getHttpFileSize();
            }
        } else {
            length = conn.getContentLength();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        disconnect(conn);
    }

    log("Content length is " + length + " bytes");

    return length;
}

From source file:net.sf.golly.HelpActivity.java

private String downloadURL(String urlstring, String filepath) {
    // download given url and save data in given file
    try {/*from w ww  . j  a  va2 s .  co  m*/
        File outfile = new File(filepath);
        final int BUFFSIZE = 8192;
        FileOutputStream outstream = null;
        try {
            outstream = new FileOutputStream(outfile);
        } catch (FileNotFoundException e) {
            return "File not found: " + filepath;
        }

        long starttime = System.nanoTime();

        // Log.i("downloadURL: ", urlstring);
        URL url = new URL(urlstring);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setAllowUserInteraction(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestMethod("GET");
        connection.connect();
        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            outstream.close();
            return "No HTTP_OK response.";
        }

        // init info for progress bar
        int filesize = connection.getContentLength();
        int downloaded = 0;
        int percent;
        int lastpercent = 0;

        // stream the data to given file
        InputStream instream = connection.getInputStream();
        byte[] buffer = new byte[BUFFSIZE];
        int bufflen = 0;
        while ((bufflen = instream.read(buffer, 0, BUFFSIZE)) > 0) {
            outstream.write(buffer, 0, bufflen);
            downloaded += bufflen;
            percent = (int) ((downloaded / (float) filesize) * 100);
            if (percent > lastpercent) {
                progbar.setProgress(percent);
                lastpercent = percent;
            }
            // show proglayout only if download takes more than 1 second
            if (System.nanoTime() - starttime > 1000000000L) {
                runOnUiThread(new Runnable() {
                    public void run() {
                        proglayout.setVisibility(LinearLayout.VISIBLE);
                    }
                });
                starttime = Long.MAX_VALUE; // only show it once
            }
            if (cancelled)
                break;
        }
        outstream.close();
        connection.disconnect();
        if (cancelled)
            return "Cancelled.";

    } catch (MalformedURLException e) {
        return "Bad URL string: " + urlstring;
    } catch (IOException e) {
        return "Could not connect to URL: " + urlstring;
    }
    return ""; // success
}

From source file:RhodesService.java

public static boolean pingHost(String host) {
    HttpURLConnection conn = null;
    boolean hostExists = false;
    try {/*from w w w.ja  v  a2 s .com*/
        URL url = new URL(host);
        HttpURLConnection.setFollowRedirects(false);
        conn = (HttpURLConnection) url.openConnection();

        conn.setRequestMethod("HEAD");
        conn.setAllowUserInteraction(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setConnectTimeout(10000);
        conn.setReadTimeout(10000);

        hostExists = (conn.getContentLength() > 0);
        if (hostExists)
            Logger.I(TAG, "PING network SUCCEEDED.");
        else
            Logger.E(TAG, "PING network FAILED.");
    } catch (Exception e) {
        Logger.E(TAG, e);
    } finally {
        if (conn != null) {
            try {
                conn.disconnect();
            } catch (Exception e) {
                Logger.E(TAG, e);
            }
        }
    }

    return hostExists;
}