我学习Java通过使用教科书,其中包含描述使用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提供的URLConnection的子类,提供了对HTTP连接的支持。 这个类叫做HttpURLConnection。通过调用URL对象上的openConnection(),您可以获得与刚刚显示的 相同的HttpURLConnection,但您必须将结果 转换为HttpURLConnection。 (当然,你必须确保你实际上是打开一个 HTTP连接。)一旦你获得一个HttpURLConnection的对象, 你可以使用任何从URLConnection的