Java 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.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/

相关文章:

android - 在 Android 中使用 HttpURLConnection 从 url 获取 xml

java - 在 Java 中为生产者/消费者模式创建同步缓冲区

java - 通过存储uri获取azure订阅id

java - Eclipse CDT ASTRewrite 不工作

c++ - 构造函数中的打印函数

java - 在 Apache Tomcat 中多次调用 REST 服务构造函数

java - 如何解决 NoClassDefFoundError Java 代理

java - 如何从构造函数中设置 JavaFX 中 TextArea 的文本?

java - 检查 Android 上的页面是否已启动会导致崩溃吗?

java - 如何解决 SSL 握手异常