我正在通过一本教科书学习 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/