问题描述
我使用的凯文Sawicki的图书馆在我的Android应用程序的HTTP请求。图书馆方法提出请求的实际调用是在一个类文件名为制成(它无法从活动的称呼) TemplateHelper
。在我TemplateHelper类调用的Htt prequest库的方法看起来像这样
I am using Kevin Sawicki's library for HTTP requests in my Android application. The actual call to the library methods for making the request is made in a class file (it's not called from an activity) called TemplateHelper
. The method that calls the HttpRequest library in my TemplateHelper class looks like this
public static JSONObject GetTemplates() {
try {
return new JSONObject(HttpRequest.get("http://myapi.mycompany.com/templates").body());
} catch (HttpRequestException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
从我的活动我再调用 TemplateHelper.GetTemplates()
来获取数据。然而,当我做到这一点的Android抛出异常 android.os.NetworkOnMainThreadException
。
快速谷歌搜索显示我code为一个单独的线程运行HTT prequest。但是,如果我运行在一个单独的线程code,我怎么能结果返回到主线程?
From my activity i then call TemplateHelper.GetTemplates()
to get the data. However, when i do this Android throws the exception android.os.NetworkOnMainThreadException
.A quick Google search shows me the code for running the HTTPRequest on a separate thread. But if i run the code in a separate thread, how can i return the result to the main thread?
推荐答案
您不能让在主线程网络请求。你会得到你现在所看到的错误。您需要为使用的AsyncTask
或你需要创建一个新的线程。就个人而言,我会使用的AsyncTask
。当您使用的AsyncTask
您可以使用 onPostExecute
方法的返回值主线程。
You can't make network requests on the main thread. You'll get the error you are seeing now. You need to use either AsyncTask
or you need to create a new thread. Personally, I'd use AsyncTask
. When you use AsyncTask
you can use the onPostExecute
method to return the value to the main thread.
这篇关于在主线程错误Android的http请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!