2011-05-30 24 views
0

在Java代碼中運行時,可從瀏覽器訪問的URL提供404響應代碼。在java代碼中無法訪問的URL

是什麼問題? ..Can誰能解釋我這個

public String login(String url) { 
     URL targetURL; 
     long start = 0; 
     long end = 0; 
     float difference = 0; 
     HttpURLConnection httpURLConnection; 
     StringBuffer strbufstatus = new StringBuffer(); 
     try { 
      //Connecting to the url 
      targetURL = new URL(url); 

      start = System.currentTimeMillis(); 

      httpURLConnection = (HttpURLConnection) targetURL.openConnection(); 

      httpURLConnection.setUseCaches(false); 

      httpURLConnection.setAllowUserInteraction(false); 

      httpURLConnection.setDoInput(true); 

      httpURLConnection.setRequestMethod("GET"); 

      httpURLConnection.connect(); 

      //Getting the respond Code 
      int responseCode = httpURLConnection.getResponseCode(); 

      strbufstatus.append("Response Code===> " + responseCode + "<br>"); 

      if(responseCode==200){ 


      // System.out.println("respondcode===> " + responseCode); 

      end = System.currentTimeMillis(); 

      //Calculating the response time 

      difference = (end - start); 

      difference = difference/1000; 

      // System.out.println("Response Time===> " + difference); 

      strbufstatus.append("Rsponse time===> " + difference + "<br>"); 
      } 
      } catch (IOException ex) { 
      if (ex.toString().contains("java.net.UnknownHostException:")) { 

       strbufstatus.append(" - UnknownHostException has occured during Httpconnection\n"); 
      } else if (ex.toString().contains("java.net.MalformedURLException: unknown protocol:")) { 
       strbufstatus.append(" - Unknown Protocol\n"); 
      } else if (ex.toString().contains("java.net.ConnectException: Connection timed out: connect")) { 
       strbufstatus.append("Connection TimedOut\n"); 
      } else { 
       strbufstatus.append("IOException has occured during Httpconnection \n"); 
      } 
      ex.printStackTrace(); 
     } 
     System.out.println("Status" +strbufstatus); 
     return strbufstatus.toString(); 


    } 
+0

謹慎顯示一些代碼? – 2011-05-30 12:21:40

+0

沒有示例代碼?檢查特殊字符 – Max 2011-05-30 12:21:54

+0

添加代碼..請檢查 – Rachel 2011-05-30 12:31:38

回答

5

以下可問題:

  • 錯誤代碼(打開代碼,如果你對這種情況下懷疑)
  • 你是落後的代理,瀏覽器有得到它被配置,但是你的程序有沒有
  • ,如果你試圖訪問安全URL HTTPS,則證書配置
+2

+1 - 根據我的經驗,代理問題是最有可能的問題。 – 2011-05-30 13:10:41

1

從維基百科對錯誤代碼404:

404或未找到的錯誤消息是一個HTTP標準響應代碼,指示客戶端能夠與服務器通信,但服務器找不到請求的內容。

應該有一個人類可讀的「理由短語」解釋什麼還沒有找到。你只是讀響應碼 - 讀取和打印另外:

String responseMessage = httpUrlConnection.responseMessage(); 
0

一種可能性是,在URL中包含某些字符不是有效的URL,例如空間或ASCII範圍之外的東西。這需要以某種方式進行轉換以作爲URL發送,例如%HH轉義序列。瀏覽器在您輸入地址時會自動執行此操作,但它們並非全都以相同的方式進行操作。例如,有些使用現在推薦的轉換爲UTF-8序列的約定,但有些使用ISO-8859-1。有些將空間轉換爲+,另一些轉換爲%20。如果您希望程序以與瀏覽器相同的方式處理URL,則必須在Java代碼中執行正確的編碼。