安卓的AsyncTask使一个HTTP GET请求? [英] Android: AsyncTask to make an HTTP GET Request?

查看:100
本文介绍了安卓的AsyncTask使一个HTTP GET请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的Andr​​oid的发展。我的问题是,我为了让HTTP GET请求(JSON响应)使用AsyncTask的?它是否正确?有谁知道在哪里我可以看到这样的例子,如果这确实是真的吗?如果没有,你能指正?谢谢!

I'm new to Android development. My question is, do I use AsyncTask in order to make an HTTP GET request (JSON response)? Is this correct? Does anyone know where I can see an example of this if this is indeed true? If not, could you correct me? Thanks!

推荐答案

是的,你说得对,AsyncTask的用于短期运行的任务,例如连接到网络。此外,它是用于后台任务,这样你不会阻止你的UI线程或获取异常,因为你不能做你的UI /主线程的网络连接。

Yes you are right, Asynctask is used for short running task such as connection to the network. Also it is used for background task so that you wont block you UI thread or getting exception because you cant do network connection in your UI/Main thread.

例如:

class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {


@Override
protected void onPreExecute() {
    super.onPreExecute();

}

@Override
protected Boolean doInBackground(String... urls) {
    try {

        //------------------>>
        HttpGet httppost = new HttpGet("YOU URLS TO JSON");
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response = httpclient.execute(httppost);

        // StatusLine stat = response.getStatusLine();
        int status = response.getStatusLine().getStatusCode();

        if (status == 200) {
            HttpEntity entity = response.getEntity();
            String data = EntityUtils.toString(entity);


            JSONObject jsono = new JSONObject(data);

            return true;
        }


    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {

        e.printStackTrace();
    }
    return false;
}

protected void onPostExecute(Boolean result) {

}

这篇关于安卓的AsyncTask使一个HTTP GET请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆