2013-09-24 112 views
0

我很難將應用程序連接到互聯網並檢索html源代碼。 一直在尋找解決方案,並沒有找到。希望有人能幫助。 這裏是我的代碼:安卓網絡連接faliure

public class Main extends Activity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     final EditText et = (EditText) findViewById(R.id.editText1); 
     final Button b = (Button) findViewById(R.id.button1); 
     final TextView tv = (TextView) findViewById(R.id.textView1); 

     b.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 

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

       } catch (Exception e) { 

       } 

      } 
     }); 
    } 

我還添加INTERNET權限..

+0

會發生什麼?它不編譯?它是否例外?它在logcat上打印什麼? – user2259824

+0

Internet請求不應位於主線程中。 – goodm

+0

readLine方法可能會阻塞該線程。你應該在自己的線程中做到這一點。 – user2259824

回答

1

您需要將它連接到互聯網並獲取數據到AsyncTask的代碼。這是因爲NetworkOnMainThreadException。當應用程序嘗試在其主線程上執行聯網操作時,會引發此異常。

儘管可以使用StrictMode.ThreadPolicy解決方法,但強烈建議您不要這樣做。

這裏是摘自docs

NetworkOnMainThreadException: -

這只是拋出應用 針對蜂窩SDK或更高。針對較早的 SDK版本的應用程序允許在其主要事件循環 線程上進行聯網,但極不鼓勵。

有關更多信息,請參閱this question

0

因爲你在UI therad上做了這個。

試試這個:

公共類主要擴展活動{

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    final EditText et = (EditText) findViewById(R.id.editText1); 
    final Button b = (Button) findViewById(R.id.button1); 
    final TextView tv = (TextView) findViewById(R.id.textView1); 

    b.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      Thread th = new Thread() { 
       @Override 
       public void run() { 
        try { 

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

       } catch (Exception e) { 

       } 
      } 
     }; 
     th.start(); 
     } 
    }); 
} 
+0

非常感謝!!,這個工作非常棒! 我猜測,它以某種方式連接到前面的傢伙的答案.. – evyamiz

+0

MM ..那麼重點是,你需要在主線程以外的線程中執行互聯網的東西。 :)乾杯 –

0

我會建議你使用AsyncTask

做這個

ButtonClick

RequestClient reqClient = new RequestClient(ActivityName.this); 
String AppResponse = null; 
AppResponse = reqClient.execute().get(); 

RequestClient

public class RequestClient extends AsyncTask<String, Void, String> { 
    Context context; 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 

    } 

    @Override 
    protected String doInBackground(String... params) { 
     try { 
      HttpClient httpclient = new DefaultHttpClient(); // Create HTTP Client 
      HttpGet httpget = new HttpGet("http://yoururl.com"); // Set the action you want to do 
      HttpResponse response = httpclient.execute(httpget); // Executeit 
      HttpEntity entity = response.getEntity(); 
      InputStream is = entity.getContent(); // Create an InputStream with the response 
      BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); 
      StringBuilder sb = new StringBuilder(); 
      String line = null; 
      while ((line = reader.readLine()) != null) // Read line by line 
      sb.append(line + "\n"); 

      String resString = sb.toString(); // Result is here 

      is.close(); // Close the stream 
      } catch (Exception e) { 
      Log.d("ANDRO_ASYNC_ERROR", "Error is " + e.toString()); 
     } 
     Log.d("ANDRO_ASYNC_RESPONSE", responseString.trim()); 
     client.getConnectionManager().shutdown(); 
     return responseString.trim(); 
    } 

    @Override 
    protected void onPostExecute(String result) { 
     // TODO Auto-generated method stub 
     super.onPostExecute(result); 

    } 
}