Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-1257160

getContentLength in URLConnection does not work

XMLWordPrintable

    • 1.1
    • generic
    • solaris_2.4
    • Not verified

      [prasadw 96/06/26]

      import java.net.*;
      import java.io.*;

      class T {
          public static void main(String argv[]) {
              String host = "haven";
              int port = 8888;
              String protocol = "http";
              try {
                  URL url = new URL(protocol, host, port, "/servlet/rulesadmin");
                  URLConnection urlcon = url.openConnection();
                  int length = urlcon.getContentLength();
                  System.out.println("getAction: length " + length);
                  InputStream is = urlcon.getInputStream();
                  byte[] b = new byte[length];
                  is.read(b);
                  String str = new String(b, 0);
                  System.out.println(str);
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
      }


      prints

      getAction: length -1
      java.lang.NegativeArraySizeException
      at T.main(T.java:16)


      even though the server returns valid content length.

      3954$ telnet haven 8888
      Trying 129.144.175.60...
      Connected to haven.
      Escape character is '^]'.
      GET /servlet/rulesadmin HTTP/1.0

      HTTP/1.0 200 OK
      Server: Jeeves
      Content-Length: 1154
      Date: 27 Jun 1996 05:17:26 GMT

      # rules properties
      # Name translation rules for files, cgi and servlets.
      #
      # The two possible formats are:
      #
      # For file translations
      # Rn.virtualPath=/x/y
      ....


      [prasadw 96/06/26]

      If we call getContentType before getContentLength, things work fine:

      import java.net.*;
      import java.io.*;

      class T {
          public static void main(String argv[]) {
              String host = argv[0];
              int port = Integer.parseInt(argv[1]);
              String protocol = "http";
              String file = argv[2];
              try {
                  URL url = new URL(protocol, host, port, file);
                  URLConnection urlcon = url.openConnection();
                  System.out.println(urlcon.getContentType());
                  System.out.println(urlcon.getContentLength());
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
      }

      returns

      4047$ java T haven 8888 /
      text/html
      474

            busersunw Btplusnull User (Inactive)
            duke J. Duke
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: