我學習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的