2012-10-06 144 views
0

我想獲取用戶輸入的網頁的源代碼。當他按下按鈕時,他應該在TextView中看到源代碼。這是我的代碼:Android獲取網頁源代碼

final Button b = (Button) findViewById(R.id.button1); 

     b.setOnClickListener(new OnClickListener() { 

      public void onClick(View v) { 
       // TODO Auto-generated method stub 

       try { 
        URL url = null; 
        url = new URL(myEditText.getText().toString()); 
        URLConnection conn = url.openConnection(); 
        BufferedReader reader = new BufferedReader(
          new InputStreamReader(conn.getInputStream())); 
        String line = ""; 
        while ((line = reader.readLine()) != null) { 
         myTextView.append(line); 

        } 

       } catch (Exception e) { 

        Log.e("ERR",e.getMessage()); 
       } 

      } 
     }); 

當我運行它,我在

BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); 

.-->的println需要一個消息得到一個NullPointerException。

我不知道什麼是錯的,因爲這是來自視頻教程。我已在清單中寫入<uses-permission android:name="android.permission.INTERNET"/>,所以一切都應該是好的。

+0

您可以添加堆棧跟蹤? –

+0

我懷疑你的URL是空的。這是否需要在EditText中,並且可以驗證其價值? –

回答

0

試試這個。

url = new URL("http://www.stackoverflow.com"); 

,如果它工作,那麼你需要的設置驗證像isValidUrl()

因爲用戶可能輸入了錯誤的URL。

+0

它說:協議未找到 – Teo

+0

我如何得到一些網頁的HTML源代碼?如果我獲得完整的源頁面,它可能會花費很多時間,我不需要獲得所有的線路,你能幫助我嗎? thx非常 –

0
if(!TextUtils.isEmpty(myEditText.getText())) 
      url = new URL(myEditText.getText().toString()); 
else 
url=""; 

,或者如果您正在使用最新版本檢查StrictMode並刪除它

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
    StrictMode.setThreadPolicy(policy); 

還檢查Android是網絡提供或不