0

I am currently writing a simple proxy server that accepts connection from my web browser. The problem is I cannot visit my school website at ice.xjtlu.edu.cn whereas my friend has no problem visiting it. It throws a NullPointerException at the line where read() is called.

private static final int BUFFER_SIZE = 32768;
public void run() {

    try {
        DataOutputStream out = new DataOutputStream(socket.getOutputStream());
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); //convert input to string

        String temp = "";
        temp = in.readLine();
        String[] tempArr = temp.split(" ");

        System.out.println("Type of connection: " + tempArr[0]);
        System.out.println("URL of website: " + tempArr[1]);
        System.out.println(tempArr[2]);

        BufferedReader rd = null;
        try {
            System.out.println("Sending request to: " + tempArr[1]);

            URL url = new URL(tempArr[1]);
            URLConnection conn = url.openConnection();
            conn.setDoInput(true);
            // not doing HTTP posts
            conn.setDoOutput(false);

            InputStream is = null;
            HttpURLConnection huc = (HttpURLConnection) conn;
            if (huc.getContentLength() > 0) {
                try {
                    is = huc.getInputStream();
                    rd = new BufferedReader(new InputStreamReader(is));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            byte[] by = new byte[BUFFER_SIZE];

            int index = is.read(by, 0, BUFFER_SIZE);

            while (index != -1) {
                out.write(by, 0, index);
                index = is.read(by, 0, BUFFER_SIZE);
            }
            out.flush();
        } catch (IOException e) {
            System.out.println(e);
            System.out.println("is it this one");
            out.writeBytes("");
        }
      //close sockets

I've read through the documentation for the read() method and NullPointerException will be thrown only if the byte[] is NULL.
However, how could the byte[] be NULL if it is always initialized to a size of 32768 prior to read() ?

Thomas
  • 1,445
  • 14
  • 30
Leonardo Vinsen
  • 89
  • 1
  • 12
  • 1
    It will also be thrown if `is` is null, which it could easily be - because if an `IOException` is thrown when you're assigning to it, you're just printing out the stack trace and continuing. Likewise if the content length is 0, you're never assigning a non-null value to `is`... – Jon Skeet Nov 06 '16 at 09:36
  • Don't write code like this. Code that depends on the success of code in a `try` block should be inside that `try` block. – user207421 Nov 06 '16 at 09:39
  • @JonSkeet thanks for the advice. I found out that when visiting ice.xjtlu.edu.cn the content length was -1, so I removed the IF clause and now it is working. – Leonardo Vinsen Nov 06 '16 at 10:02

0 Answers0