Java URL连接
简单的事情,我正在课堂上学习 URL/网络,并且我正在尝试在网页上显示一些内容。稍后我将把它连接到 MySQL 数据库...无论如何,这是我的程序:
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 在 asp.main(asp.java:17)
第 17 行:InputStream response = connection.getInputStream();
谢谢, 担
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您有一个格式错误的 URL,但您不会知道,因为您吞下了它的异常!
此 URL 不完整,它缺少主机(对于您来说可能是
localhost
?),以及协议部分,比如http
,这样可以避免格式错误的 URL 异常 您必须提供包括协议的完整 URL使用 URLConnection。该代码片段至少可以工作,如果您用有效 URL 替换该示例中的 URL,您应该拥有一段有效的代码。
You have a malformed URL, but you wouldn't know because you swallowed its exception!
This URL is not complete, it misses the host (maybe
localhost
for you?), and the protocol part, sayhttp
so to avoid the malformed URL exception you have to provide the full URL including the protocolUse 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.
这是因为您的网址无效。您需要将完整地址放入您尝试打开连接的页面。您正在捕获 malformedurlexception,但这意味着此时没有“连接”对象。在第一个 catch 块出现之后,您还有一个额外的闭括号。您应该将要获取空指针的行和 system.out.println 放在 catch 块上方
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