2015-03-18 73 views
-1

我有這個應用程序強制關閉此代碼,我做錯了什麼?如何通過HTTP檢索網站?

public void buscaAno(View v){ 

    HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost("http://sapires.netne.net/teste.php?formato=json&idade=55"); 
    try { 
     HttpResponse response = httpclient.execute(httppost); 
     final String str = EntityUtils.toString(response.getEntity()); 

     TextView tv = (TextView) findViewById(R.id.idade); 
     tv.setText(str); 
    } 
    catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

} 
+0

你在主線程中執行這個代碼?你得到一個android.os.NetworkOnMainThreadException? – 2015-03-18 21:30:50

回答

1

看起來這是onClick監聽器,它在主線程上執行阻塞操作,進而導致ANR或NetworkOnMainThreadException。您應該使用AsyncTaskService爲您的目的。

例如,你可以擴展的AsyncTask方式如下:

private class PostRequestTask extends AsyncTask<String, Void, String> { 
     protected String doInBackground(String... strings) { 
      HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost(strings[0]); 

      try { 
       HttpResponse response = httpclient.execute(httppost); 
       return EntityUtils.toString(response.getEntity()); 
      } catch (IOException e) { 
       //Handle exception here 
      } 
     } 

     protected void onPostExecute(String result) { 
      TextView textView = (TextView) findViewById(R.id.idade); 
      textView.setText(result); 
     } 
    } 

,然後用它是這樣的:

public void buscaAno(View v) { 
     new PostRequestTask().execute("http://sapires.netne.net/teste.php?formato=json&idade=55"); 
    }