Example usage for java.net URLConnection getContentLength

List of usage examples for java.net URLConnection getContentLength

Introduction

In this page you can find the example usage for java.net URLConnection getContentLength.

Prototype

public int getContentLength() 

Source Link

Document

Returns the value of the content-length header field.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    int size;/*www . j a  va 2  s  .  c om*/
    URL url = new URL("http://www.server.com");
    URLConnection conn = url.openConnection();
    size = conn.getContentLength();
    if (size < 0)
        System.out.println("Could not determine file size.");
    else
        System.out.println(size);
    conn.getInputStream().close();

}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    int c;/*from   w  w w  .  jav a 2 s .  c  om*/
    URL hp = new URL("http", "www.java2s.com", 80, "/");
    URLConnection hpCon = hp.openConnection();
    if (hpCon.getContentLength() > 0) {
        InputStream input = hpCon.getInputStream();
        int i = hpCon.getContentLength();
        while (((c = input.read()) != -1) && (--i > 0)) {
            System.out.print((char) c);
        }
        input.close();
    } else {
        System.out.println("No Content Available");
    }
}

From source file:MainClass.java

public static void main(String args[]) throws Exception {

    URL u = new URL("http://www.java2s.com/binary.dat");
    URLConnection uc = u.openConnection();
    String contentType = uc.getContentType();
    int contentLength = uc.getContentLength();
    if (contentType.startsWith("text/") || contentLength == -1) {
        throw new IOException("This is not a binary file.");
    }/* w ww  .  j a v  a2s.c o m*/
    InputStream raw = uc.getInputStream();
    InputStream in = new BufferedInputStream(raw);
    byte[] data = new byte[contentLength];
    int bytesRead = 0;
    int offset = 0;
    while (offset < contentLength) {
        bytesRead = in.read(data, offset, data.length - offset);
        if (bytesRead == -1)
            break;
        offset += bytesRead;
    }
    in.close();

    if (offset != contentLength) {
        throw new IOException("Only read " + offset + " bytes; Expected " + contentLength + " bytes");
    }

    String filename = u.getFile().substring(filename.lastIndexOf('/') + 1);
    FileOutputStream out = new FileOutputStream(filename);
    out.write(data);
    out.flush();
    out.close();
}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    int c;//from   www  .  jav  a2s.c  om
    URL hp = new URL("http", "www.java2s.com", 80, "/");
    URLConnection hpCon = hp.openConnection();
    System.out.println("Date: " + hpCon.getDate());
    System.out.println("Type: " + hpCon.getContentType());
    System.out.println("Exp: " + hpCon.getExpiration());
    System.out.println("Last M: " + hpCon.getLastModified());
    System.out.println("Length: " + hpCon.getContentLength());
}

From source file:Main.java

public static void main(String args[]) throws Exception {

    URL u = new URL("http://www.java2s.com");
    URLConnection uc = u.openConnection();
    System.out.println("Content-type: " + uc.getContentType());
    System.out.println("Content-encoding: " + uc.getContentEncoding());
    System.out.println("Date: " + new Date(uc.getDate()));
    System.out.println("Last modified: " + new Date(uc.getLastModified()));
    System.out.println("Expiration date: " + new Date(uc.getExpiration()));
    System.out.println("Content-length: " + uc.getContentLength());
}

From source file:Main.java

public static void main(String args[]) throws Exception {

    URL u = new URL("http://www.java2s.com");
    URLConnection uc = u.openConnection();
    uc.connect();/*from   w ww .  jav  a  2  s .c  o m*/
    System.out.println("Content-type: " + uc.getContentType());
    System.out.println("Content-encoding: " + uc.getContentEncoding());
    System.out.println("Date: " + new Date(uc.getDate()));
    System.out.println("Last modified: " + new Date(uc.getLastModified()));
    System.out.println("Expiration date: " + new Date(uc.getExpiration()));
    System.out.println("Content-length: " + uc.getContentLength());
}

From source file:OldExtractor.java

/**
 * @param args the command line arguments
 *///from   w  w w .j  a v  a2s .c om
public static void main(String[] args) {
    // TODO code application logic here
    String bingUrl = "https://api.datamarket.azure.com/Bing/Search/Web?$top=10&$format=Atom&Query=%27gates%27";
    //Provide your account key here.
    String accountKey = "ghTYY7wD6LpyxUO9VRR7e1f98WFhHWYERMcw87aQTqQ";
    //  String accountKey = "xqbCjT87/MQz25JWdRzgMHdPkGYnOz77IYmP5FUIgC8";

    byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes());
    String accountKeyEnc = new String(accountKeyBytes);

    try {
        URL url = new URL(bingUrl);
        URLConnection urlConnection = url.openConnection();

        urlConnection.setRequestProperty("Authorization", "Basic " + accountKeyEnc);
        InputStream inputStream = (InputStream) urlConnection.getContent();
        byte[] contentRaw = new byte[urlConnection.getContentLength()];
        inputStream.read(contentRaw);
        String content = new String(contentRaw);
        //System.out.println(content);
        try {
            File file = new File("Results.xml");
            FileWriter fileWriter = new FileWriter(file);
            fileWriter.write(content);
            //fileWriter.write("a test");
            fileWriter.flush();
            fileWriter.close();

        } catch (IOException e) {
            System.out.println(e);
        }

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        try {
            //System.out.println("here");
            //Using factory get an instance of document builder
            DocumentBuilder db = dbf.newDocumentBuilder();

            //parse using builder to get DOM representation of the XML file
            Document dom = db.parse("Results.xml");
            Element docEle = (Element) dom.getDocumentElement();

            //get a nodelist of elements

            NodeList nl = docEle.getElementsByTagName("d:Url");
            if (nl != null && nl.getLength() > 0) {
                for (int i = 0; i < nl.getLength(); i++) {

                    //get the employee element
                    Element el = (Element) nl.item(i);
                    // System.out.println("here");
                    System.out.println(el.getTextContent());

                    //get the Employee object
                    //Employee e = getEmployee(el);

                    //add it to list
                    //myEmpls.add(e);
                }
            }
            NodeList n2 = docEle.getElementsByTagName("d:Title");
            if (n2 != null && n2.getLength() > 0) {
                for (int i = 0; i < n2.getLength(); i++) {

                    //get the employee element
                    Element e2 = (Element) n2.item(i);
                    // System.out.println("here");
                    System.out.println(e2.getTextContent());

                    //get the Employee object
                    //Employee e = getEmployee(el);

                    //add it to list
                    //myEmpls.add(e);
                }
            }

            NodeList n3 = docEle.getElementsByTagName("d:Description");
            if (n3 != null && n3.getLength() > 0) {
                for (int i = 0; i < n3.getLength(); i++) {

                    //get the employee element
                    Element e3 = (Element) n3.item(i);
                    // System.out.println("here");
                    System.out.println(e3.getTextContent());

                    //get the Employee object
                    //Employee e = getEmployee(el);

                    //add it to list
                    //myEmpls.add(e);
                }
            }

        } catch (SAXException se) {
            se.printStackTrace();
        } catch (ParserConfigurationException pe) {
            pe.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

    } catch (IOException e) {
        System.out.println(e);
    }

    //The content string is the xml/json output from Bing.

}

From source file:Main.java

public static void main(String args[]) throws Exception {
    int c;//  w w w.j  a v a2 s.c o  m
    URL hp = new URL("http://www.internic.net");
    URLConnection hpCon = hp.openConnection();

    long d = hpCon.getDate();
    if (d == 0)
        System.out.println("No date information.");
    else
        System.out.println("Date: " + new Date(d));

    System.out.println("Content-Type: " + hpCon.getContentType());

    d = hpCon.getExpiration();
    if (d == 0)
        System.out.println("No expiration information.");
    else
        System.out.println("Expires: " + new Date(d));

    d = hpCon.getLastModified();
    if (d == 0)
        System.out.println("No last-modified information.");
    else
        System.out.println("Last-Modified: " + new Date(d));

    int len = hpCon.getContentLength();
    if (len == -1)
        System.out.println("Content length unavailable.");
    else
        System.out.println("Content-Length: " + len);

    if (len != 0) {
        InputStream input = hpCon.getInputStream();
        int i = len;
        while (((c = input.read()) != -1)) { // && (--i > 0)) {
            System.out.print((char) c);
        }
        input.close();

    } else {
        System.out.println("No content available.");
    }

}

From source file:URLConnectionTest.java

public static void main(String[] args) {
    try {/* ww w  . j av  a  2s. co m*/
        String urlName;
        if (args.length > 0)
            urlName = args[0];
        else
            urlName = "http://java.sun.com";

        URL url = new URL(urlName);
        URLConnection connection = url.openConnection();

        // set username, password if specified on command line

        if (args.length > 2) {
            String username = args[1];
            String password = args[2];
            String input = username + ":" + password;
            String encoding = base64Encode(input);
            connection.setRequestProperty("Authorization", "Basic " + encoding);
        }

        connection.connect();

        // print header fields

        Map<String, List<String>> headers = connection.getHeaderFields();
        for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
            String key = entry.getKey();
            for (String value : entry.getValue())
                System.out.println(key + ": " + value);
        }

        // print convenience functions

        System.out.println("----------");
        System.out.println("getContentType: " + connection.getContentType());
        System.out.println("getContentLength: " + connection.getContentLength());
        System.out.println("getContentEncoding: " + connection.getContentEncoding());
        System.out.println("getDate: " + connection.getDate());
        System.out.println("getExpiration: " + connection.getExpiration());
        System.out.println("getLastModifed: " + connection.getLastModified());
        System.out.println("----------");

        Scanner in = new Scanner(connection.getInputStream());

        // print first ten lines of contents

        for (int n = 1; in.hasNextLine() && n <= 10; n++)
            System.out.println(in.nextLine());
        if (in.hasNextLine())
            System.out.println(". . .");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:MainClass.java

public static void saveBinaryFile(URL u) {
    int bufferLength = 128;
    try {//w w w  .  ja v  a 2s .  c o  m
        URLConnection uc = u.openConnection();
        String ct = uc.getContentType();
        int contentLength = uc.getContentLength();
        if (ct.startsWith("text/") || contentLength == -1) {
            System.err.println("This is not a binary file.");
            return;
        }

        InputStream stream = uc.getInputStream();
        byte[] buffer = new byte[contentLength];
        int bytesread = 0;
        int offset = 0;
        while (bytesread >= 0) {
            bytesread = stream.read(buffer, offset, bufferLength);
            if (bytesread == -1)
                break;
            offset += bytesread;
        }
        if (offset != contentLength) {
            System.err.println("Error: Only read " + offset + " bytes");
            System.err.println("Expected " + contentLength + " bytes");
        }

        String theFile = u.getFile();
        theFile = theFile.substring(theFile.lastIndexOf('/') + 1);
        FileOutputStream fout = new FileOutputStream(theFile);
        fout.write(buffer);
    } catch (Exception e) {
        System.err.println(e);
    }
    return;
}