gpt4 book ai didi

Java HttpURLConnection类程序

转载 作者:行者123 更新时间:2023-11-30 06:30:51 25 4
gpt4 key购买 nike

我正在通过一本教科书学习 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 provides a subclass of URLConnection that provides support for HTTP connections. This class is called HttpURLConnection. You obtain an HttpURLConnection in the same way just shown, by calling openConnection( ) on a URL object, but you must cast the result to HttpURLConnection. (Of course, you must make sure that you are actually opening an HTTP connection.) Once you have obtained a reference to an HttpURLConnection object, you can use any of the methods inherited from URLConnection

最佳答案

你不明白为什么不用的声明:

 HttpURLConnection hpCon = new HttpURLConnection();

不提供有关要打开连接的 URL 的信息。这就是您应该使用的原因:

HttpURLConnection hpCon = new HttpURLConnection(hp);

因为通过这种方式,构造函数知道您要打开到 url "http://www.google.com" 的连接。

关于Java HttpURLConnection类程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10119067/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com