Question

Simple stuff, I am learning URLs/Networking in my class and I am trying to display something on a webpage. Later I am going to connect it to a MySQL DB... anyway here is my program:

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


public class asp {

    public static URLConnection
connection;

    public static void main(String[] args) {

        try {

        System.out.println("Hello World!"); // Display the string.
        try {
        URLConnection connection = new URL("post.php?players").openConnection();
    }catch(MalformedURLException rex) {}
        InputStream response =
connection.getInputStream();
        System.out.println(response);
    }catch(IOException ex) {}

    } }

It compiles fine... but when I run it I get:

Hello World!
Exception in thread "main" java.lang.NullPointerException at asp.main(asp.java:17)

Line 17: InputStream response = connection.getInputStream();

Thanks, Dan

Was it helpful?

Solution

It's because your URL is not valid. You need to put the full address to the page you are trying to open a connection to. You are catching the malformedurlexception but that means that there is no "connection" object at that point. You have an extra closed bracket after the first catch block it appears as well. You should put the line that you are getting the null pointer for and the system.out.println above the catch blocks

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

public class asp {

    public static URLConnection connection;

    public static void main(String[] args) {

        try {
        System.out.println("Hello World!"); // Display the string.
            try {
            URLConnection connection = new URL("http://localhost/post.php?players").openConnection();
            InputStream response = connection.getInputStream();
            System.out.println(response);

            }catch(MalformedURLException rex) {
                System.out.println("Oops my url isn't right");
        }catch(IOException ex) {}
    }    
}

OTHER TIPS

You have a malformed URL, but you wouldn't know because you swallowed its exception!

URL("post.php?players")

This URL is not complete, it misses the host (maybe localhost for you?), and the protocol part, say http so to avoid the malformed URL exception you have to provide the full URL including the protocol

new URL("http://www.somewhere-dan.com/post.php?players")

Use the Sun tutorials on URLConnection first. That snippet is at least known to work, if you substitute the URL in that example with a valid URL you should have a working piece of code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top