search

Home  >  Q&A  >  body text

android - AsyncTask进行http请求,请求到XML数据后在onPostExecute解析,为何报在主线程中执行网络请求错误。

然而将解析操作写在doInBackground方法中不会报错。

怪我咯怪我咯2772 days ago517

reply all(3)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 17:38:35

    This is the case. The poster's result(InputStream) is an InputStream pointing to a remote resource. Reading data from the InputStream at this time is equivalent to reading the remote resource, so an error will be reported. The fundamental reason is that Android's restriction on "network requests cannot be executed in the main thread" is the entire data process, not just limited to the connection ((HttpURLConnection)url.openConnection()).

    So the recommended approach is to place the entire InputStream parsing in doInBackground, and then return an entity class that conforms to the business logic in doInBackground.

    reply
    0
  • 高洛峰

    高洛峰2017-04-17 17:38:35

    Parsing is a time-consuming operation and should be placed in a sub-thread, onPostExecute是主线程,doInBackgroundis a sub-thread.

    You did a time-consuming operation on the main thread, so it’s normal to report an error.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 17:38:35

    You should replace the InputStream with the obtained data String

    Then parse in onPostExecute()

    reply
    0
  • Cancelreply