我有这个应用程序强制关闭此代码,我做错了什么?
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 :(得分:1)
似乎这是onClick侦听器,它在主线程上执行阻塞操作,这反过来导致ANR或NetworkOnMainThreadException。您应该使用AsyncTask或Service来达到目的。
例如,您可以通过以下方式扩展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");
}