2013-10-04 49 views
-1

響應代碼,我想在我的程序響應代碼 請你告訴我什麼是我下面的代碼如何獲得在Java

public class Main{ 
     public static void main(String args[]) throws Exception { 
     URL url = new URL("http://www.google.com"); 
     HttpURLConnection httpCon = openConnection(); 


     System.out.println("Response code is " + httpCon.getResponseCode()); 
    } 
    } 
+4

你看到了什麼錯誤? – Reimeus

+1

openConnection();你的意思是url.openConnection(); ?? –

+0

請給我們stacktrace /錯誤和'openConnection()'的代碼' –

回答

2
public class Main{ 
    public static void main(String args[]) throws Exception { 
    URL url = new URL("http://www.google.com"); 
    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection(); 


    System.out.println("Response code is " + httpCon.getResponseCode()); 
} 
} 
0

原因該問題的錯誤是編譯器告訴類構造函數(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(); 
     } 
    } 
0

你忘了把url 改變它HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();

package naveed.workingfiles; 

import java.net.HttpURLConnection; 
import java.net.URL; 

public class Url { 

    public static void main(String args[]) throws Exception { 
     URL url = new URL("http://www.google.com"); 
     HttpURLConnection httpCon = (HttpURLConnection) url.openConnection(); 

     System.out.println("Response code is " + httpCon.getResponseCode()); 
    } 
} 
0

嘗試鑄造對象HTTPU RLConnection

public class Main{ 
    public static void main(String args[]) throws Exception { 
    URL url = new URL("http://www.google.com"); 
    //Cast the object to HttpURLConnection 
    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection(); 
    System.out.println("Response code is " + httpCon.getResponseCode()); 
} 
} 
1

錯誤是顯而易見的人。

openConnection()URL類的一種方法,並且未在您的類中定義。您必須使用您之前創建的URL類的對象。

電話的openConnection()方法必須像這個 -

url.openConnection()它返回一個URLConnection對象,你將不得不此對象類型強制轉換爲HttpURLConnection