原因該問題的錯誤是編譯器告訴類構造函數(URL)和方法(openConnection
..)拋出異常(在它們的signatures
中定義)並採取一些必要的步驟。
你有2種選擇:
Throw
的檢查異常,從你的主要方法是。
public static void main(String[] args) throws IOException {
URL url = new URL("http://www.google.com");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
System.out.println("Response code is " +
httpCon.getResponseCode());
}
或
聽清楚Exception
,使用try catch block.
public static void main(String[] args) {
URL url;
HttpURLConnection httpCon;
try {
url = new URL("http://www.google.com");
httpCon = (HttpURLConnection) url.openConnection();
System.out.println("Response code is " + httpCon.getResponseCode());
} catch (IOException e) {
e.printStackTrace();
}
}
你看到了什麼錯誤? – Reimeus
openConnection();你的意思是url.openConnection(); ?? –
請給我們stacktrace /錯誤和'openConnection()'的代碼' –