当我从另一个线程发出请求时,我得到了NetworkOnMainThreadException eaven

时间:2012-08-30 11:28:49

标签: android android-asynctask

我理解以HoneyComb设备为目标的android.os.NetworkOnMainThreadException,但以下代码引发了相同的异常:

class MakeRequest extends AsyncTask<String,Integer,Void>
    {

        @Override
        protected Void doInBackground(String... params) {
            DefaultHttpClient cli = new DefaultHttpClient();
            try {
                String url = params[0].replace(" ", "%20");
                HttpResponse resp = cli.execute(new HttpGet(url));
                BufferedReader read = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
                String tmp = "",rezultat = "";
                setResult("");

                while ((tmp = read.readLine()) != null)
                {
                    rezultat = rezultat + tmp;
                }
                setResult(rezultat);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                setResult("");
                return null;
            }
            return null;
        }
//Sample call
HttpRequester cc = new HttpRequester();
MakeRequest test = cc.new MakeRequest();
test.doInBackground(url);

1 个答案:

答案 0 :(得分:0)

试试这个。

new MakeRequest().execute(url);