首页 文章

Java URLConnection

提问于
浏览
1

简单的东西,我在课堂上学习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) {}

    } }

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

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

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

谢谢,丹

2 回答

  • 2

    这是因为您的网址无效 . 您需要将完整地址放在您尝试打开连接的页面上 . 您正在捕获malformedurlexception,但这意味着此时没有“连接”对象 . 在第一个捕获块出现后,您还有一个额外的闭合括号 . 您应该将获取空指针的行和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) {}
        }    
    }
    
  • 3

    你有一个 malformed URL ,但你不会知道,因为你 swallowed its exception

    URL("post.php?players")
    

    这个URL是 not complete ,它错过了主机(可能 localhost 为你?)和协议部分,比如 http 所以为了避免格式错误的URL异常,你必须提供 full URL including the protocol

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

    首先使用URLConnection上的Sun教程 . 该代码段至少已知有效,如果您使用 valid URL替换该示例中的URL,则应该有一段可用的代码 .

相关问题