1

简单的东西,我在课堂上学习 URL/网络,我试图在网页上显示一些东西。稍后我要将它连接到 MySQL DB ......无论如何,这是我的程序:

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) {}

    } }

它编译得很好......但是当我运行它时,我得到:

你好世界!
asp.main(asp.java:17) 处的线程“main”java.lang.NullPointerException 中的异常

第 17 行:InputStream 响应 = connection.getInputStream();

谢谢,丹

4

2 回答 2

3

你有一个格式错误的 URL,但你不会知道,因为你吞下了它的异常

URL("post.php?players")

这个 URL不完整,它错过了主机(也许localhost是你?)和协议部分,http为了避免格式错误的 URL 异常,你必须提供包括协议在内的完整 URL

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

首先使用关于URLConnection的 Sun 教程。该片段至少是已知的,如果您将该示例中的 URL 替换为有效的URL,您应该有一段工作代码。

于 2010-07-07T23:29:56.400 回答
2

这是因为您的网址无效。您需要将完整地址放入您尝试打开连接的页面。您正在捕获格式错误的urlexception,但这意味着此时没有“连接”对象。在它出现的第一个 catch 块之后,您还有一个额外的封闭括号。您应该将获取空指针的行和 system.out.println 放在 catch 块上方

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) {}
    }    
}
于 2010-07-07T23:29:02.197 回答