2015-03-18 52 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"); 
    }