http进入android异步任务

时间:2014-10-20 14:43:14

标签: java android android-asynctask android-networking

当我实现它时,它说“NetworkOnMainThreadException”。

有人可以发布一个有效的例子吗?

我尝试了很多不同的示例和库,但它没有用。我的代码:

private class HttpGetter extends AsyncTask<URL, Void, Void> {

    @Override
    protected Void doInBackground(URL... urls) {
        // TODO Auto-generated method stub
        StringBuilder builder = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(String.valueOf(urls[0]));

        try {
            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }
                Log.v("Getter", "Your data: " + builder.toString()); //response data
            } else {
                Log.e("Getter", "Failed to download file");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }


}

2 个答案:

答案 0 :(得分:1)

你是如何调用这个类对象的? 如果你这样打电话,你就不应该得到那个例外。

new HttpGetter().excute(new URL("http://www.urlstring.com"));

或者,您可以使用以下代码运行代码,但不推荐

StrictMode.ThreadPolicy policy = new      StrictMode.ThreadPolicy.Builder().permitAll().build();

 StrictMode.setThreadPolicy(policy); 

在android manifest.xml文件中添加此权限:

<uses-permission android:name="android.permission.INTERNET"/>

答案 1 :(得分:0)

您应该执行此new HttpGetter().execute(URL)

之类的任务

请注意,AsyncTask只能执行一次。