android - AsyncTask进行http请求,请求到XML数据后在onPostExecute解析,为何报在主线程中执行网络请求错误。
怪我咯
怪我咯 2017-04-17 17:36:35
0
3
511

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

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(3)
洪涛

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.

小葫芦

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.

Ty80

You should replace the InputStream with the obtained data String

Then parse in onPostExecute()

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template