Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/392.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java HttpURLConnection类程序_Java_Constructor_Httpurlconnection - Fatal编程技术网

Java HttpURLConnection类程序

Java HttpURLConnection类程序,java,constructor,httpurlconnection,Java,Constructor,Httpurlconnection,我通过使用一本教科书学习Java,其中包含以下代码,描述了使用HttpURLConnection class HttpURLDemo { public static void main(String args[]) throws Exception { URL hp = new URL("http://www.google.com"); HttpURLConnection hpCon = (HttpURLConnection) hp.openConnect

我通过使用一本教科书学习Java,其中包含以下代码,描述了使用
HttpURLConnection

class HttpURLDemo {
    public static void main(String args[]) throws Exception {
        URL hp = new URL("http://www.google.com");
        HttpURLConnection hpCon = (HttpURLConnection) hp.openConnection();

        // Display request method.
        System.out.println("Request method is " + hpCon.getRequestMethod());
        }
    }
有人能解释一下为什么用下面的方式声明
hpCon
对象吗

HttpURLConnection hpCon = (HttpURLConnection) hp.openConnection();
而不是像这样宣布它

HttpURLConnection hpCon = new HttpURLConnection(); 
教科书作者提供了以下解释,我真的不明白

Java提供了URLConnection的一个子类,它支持HTTP连接。 此类称为HttpURLConnection。您可以在同一数据库中获得HttpURLConnection 如上所示,通过对URL对象调用openConnection(),但必须强制转换结果 连接到HttpURLConnection。(当然,您必须确保您实际上正在打开 HTTP连接。)获得对HttpURLConnection对象的引用后, 您可以使用从URLConnection继承的任何方法


您不明白为什么不使用的声明:

 HttpURLConnection hpCon = new HttpURLConnection();
不提供有关要打开连接的URL的信息。这就是为什么您应该使用:

HttpURLConnection hpCon = new HttpURLConnection(hp);

因为这样,构造函数知道您想要打开到url的连接http://www.google.com“

java.net.URLConnection
是一个抽象类,通过各种协议(
ftp
http
等)方便与各种类型的服务器进行通信

特定于协议的子类隐藏在SUN的包中,这些隐藏的类负责协议的具体实现

在您的示例中,因为您的URL是
http://www.google.com
通过解析URL,URL类的内部知道必须使用HTTP处理程序/子类。
因此,当您打开与服务器的连接时
hp.openConnection()
您得到实现HTTP协议的类的具体实例

该类是
HttpURLConnection
的一个实例(实际上是一个子类,因为
HttpURLConnection
也是
abstract
,因此可以执行以下操作:

HttpURLConnection hpCon=(HttpURLConnection)hp.openConnection();
且不获取类强制转换异常

因此,对于Java的设计,您不能像您要求的那样执行
HttpURLConnection hpCon=new-HttpURLConnection(hp);
,因为这不是设计者希望您使用这些API的方式

您需要在
URL
s和
URLConnections
周围工作,只需要担心输入/输出。
你不应该为其余的事担心