Java URL Read getRemoteFileSize(URL url)

Here you can find the source of getRemoteFileSize(URL url)

Description

get Remote File Size

License

Open Source License

Declaration

public static int getRemoteFileSize(URL url) throws IOException 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2014 Liviu Ionescu./* w  w w. ja va 2s .c  om*/
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Liviu Ionescu - initial version
 *******************************************************************************/

import java.io.IOException;

import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class Main {
    public static int getRemoteFileSize(URL url) throws IOException {

        URLConnection connection;
        while (true) {
            connection = url.openConnection();
            if (connection instanceof HttpURLConnection) {
                int responseCode = ((HttpURLConnection) connection).getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    break;
                } else {
                    if (responseCode == HttpURLConnection.HTTP_MOVED_TEMP
                            || responseCode == HttpURLConnection.HTTP_MOVED_PERM
                            || responseCode == HttpURLConnection.HTTP_SEE_OTHER) {
                        String newUrl = connection.getHeaderField("Location");
                        url = new URL(newUrl);

                        // System.out.println("Redirect to URL : " + newUrl);
                    } else {
                        throw new IOException("Failed to open connection, response code " + responseCode);
                    }
                }
            }
        }

        int length = connection.getContentLength();

        if (connection instanceof HttpURLConnection) {
            ((HttpURLConnection) connection).disconnect();
        }

        return length;
    }
}

Related

  1. getHTTPResponse(String url)
  2. getHttpResponse(String urlStr)
  3. getLastModified(HttpURLConnection conn)
  4. getLastModified(HttpURLConnection connection)
  5. getRemoteFileLength(String url)
  6. getStreamByConnection(final HttpURLConnection con)
  7. getStringFromConnection(HttpURLConnection connection)
  8. getStringFromURL(String URLString)
  9. getText(HttpURLConnection conn)