Java 如何通过HTTP检索网站?

Java 如何通过HTTP检索网站?,java,android,Java,Android,我用这个代码关闭了这个应用程序,我做错了什么 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 =

我用这个代码关闭了这个应用程序,我做错了什么

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();
    }

}

这似乎是onClick侦听器,它在主线程上执行阻塞操作,从而导致ANR或NetworkOnMainThreadException。您可能应该出于您的目的使用或

例如,可以通过以下方式扩展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);
        }
    }

您是否在主线程中执行此代码?您是否遇到android.os.NetworkOnMainThread异常?
    public void buscaAno(View v) {
        new PostRequestTask().execute("http://sapires.netne.net/teste.php?formato=json&idade=55");
    }