0

可能重复:
android.os.NetworkOnMainThreadException

我的 android 应用程序在模拟器上运行,但在手机中显示android.os.NetworkOnMainThreadException。从搜索中我知道可以使用AsyncTask. 任何机构都可以帮助我创建一个AsyncTask在按钮单击时调用 httppost 并返回响应onCreate吗?

4

1 回答 1

0

我做到了,这是代码

private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
  String response = "";
  for (String url : urls) {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);
    try {
      HttpResponse execute = client.execute(httpGet);
      InputStream content = execute.getEntity().getContent();

      BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
      String s = "";
      while ((s = buffer.readLine()) != null) {
        response += s;
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  return response;
}

@Override
protected void onPostExecute(String result) {
  textView.setText(result);
}

}

于 2012-10-29T10:45:27.503 回答