2013-03-07 43 views
0

我製作了WebConnection Java腳本,該腳本從指定網站獲取HTML。它可以工作,但是當我試圖通過將http://自動排列在前面來簡化操作時,它不起作用,儘管字符串應該是相同的(它給出了java.lang.IllegalArgumentException)。這裏是我的代碼:如果我自動將「http://」連接到前端,則Web連接不起作用

package WebConnection; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import java.net.URL; 

import javax.swing.JOptionPane; 

public class WebConnect { 
    URL netPage; 

    public WebConnect() { 
     String s = "http://"; 
     s.concat(JOptionPane.showInputDialog(null, "Enter a URL:")); 
     System.out.println(s); 
     System.out.println(getNetContent(s)); 

       //The above does not work, but the below does 

     //System.out.println(getNetContent(JOptionPane.showInputDialog(null, "Enter a URL:"))); 
    } 

    private String getNetContent(String u) { 

     try { 
      netPage = new URL(u); 
     } catch(MalformedURLException ex) { 
      JOptionPane.showMessageDialog(null, "BAD URL!"); 
      return "BAD URL"; 
     } 
     StringBuilder content = new StringBuilder(); 
     try{ 
      HttpURLConnection connection = (HttpURLConnection) netPage.openConnection(); 
      connection.connect(); 
      InputStreamReader input = new InputStreamReader(connection.getInputStream()); 
      BufferedReader buffer = new BufferedReader(input); 
      String line; 
      while ((line = buffer.readLine()) != null) { 
       content.append(line + "\n"); 
      } 
     } catch(IOException e){ 
      JOptionPane.showMessageDialog(null, "Something went wrong!"); 
      return "There was a problem."; 
     } 
     return content.toString(); 
    } 

    public static void main(String[] args) { 
     new WebConnect(); 

    } 

例如,如果我跑WEBCONNECT(第一部分),然後鍵入google.com這是行不通的,但如果我運行註釋掉線代替,並鍵入http://google.com,它並沒有給一個錯誤。爲什麼?

在此先感謝!

回答

2

字符串是不可變的。這意味着你不能編輯內容。

更改...

String s = "http://"; 
s.concat(JOptionPane.showInputDialog(null, "Enter a URL:")); 

要...

String s = "http://"; 
s = s.concat(JOptionPane.showInputDialog(null, "Enter a URL:")); 
+0

即使我是這麼認爲的,但是當我看到這個被難住了。 [MUTABLE STRING](http://stackoverflow.com/questions/11146255/create-a-mutable-java-lang-string)。你的回答是正確的:) – SudoRahul 2013-03-07 16:18:15

+0

是的,但我有點類似私有方法可以通過反射訪問的方式,這不是真的可以這麼說。由於私人方法的內容可能發生變化,因此並不完全可靠。 – david99world 2013-03-07 16:21:23