简单的东西,我在我的课堂上学习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) {}
} }它编译得很好..。但当我运行它时,我得到:
你好,世界! 线程"main“java.lang.NullPointerException at asp.main(asp.java:17)中的异常
第17行: InputStream响应= connection.getInputStream();
谢谢你,丹
发布于 2010-07-07 23:29:02
这是因为您的URL无效。您需要将完整的地址放在要打开连接的页面上。您正在捕获malformedurlexception,但这意味着此时没有"connection“对象。在第一个catch块之后,您有一个额外的封闭括号,它也会出现。您应该将获得null指针的行和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-07 23:29:56
您有一个格式错误的URL,但是您不会知道,因为您吞下了它的异常!
URL("post.php?players")这个网址是不完整的,它错过了主机(可能是localhost?)和协议部分,比如http,因此为了避免格式错误的URL异常,您必须提供完整的URL,包括协议。
new URL("http://www.somewhere-dan.com/post.php?players")首先使用URLConnection上的Sun教程。这段代码段至少可以工作,如果用有效的 URL替换该示例中的URL,则应该有一段工作代码。
https://stackoverflow.com/questions/3199645
复制相似问题