使用 AsyncTask 异步请求网络数据

package com.ce.myasynctask;

import java.io.IOException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListView;

import com.baway.test.vo.Data;
import com.baway.test.vo.SuperClass;
import com.google.gson.Gson;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        // 找到控件
        ListView listview = (ListView) findViewById(R.id.listview);

        AsyncTask asyncTask = new AsyncTask<Void, Void, String>() {

            @Override
            protected String doInBackground(Void... params) {
                String result = null;
                // 请求数据
                HttpGet get = new HttpGet(
                        "http://m.yunifang.com/yunifang/mobile/goods/getall?random=9949&encode=6c2154232994e7d36ad461e3caa68ca7");
                HttpParams parms = new BasicHttpParams();
                HttpConnectionParams.setConnectionTimeout(parms, 5000);
                HttpConnectionParams.setSoTimeout(parms, 5000);
                HttpClient client = new DefaultHttpClient(parms);
                HttpResponse execute;
                try {
                    execute = client.execute(get);
                    if (execute.getStatusLine().getStatusCode() == 200) {
                        HttpEntity entity = execute.getEntity();
                        result = EntityUtils.toString(entity, "utf-8");

                    }
                } catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                return result;
            }

            @Override
            protected void onPostExecute(String result) {
                Gson gson = new Gson();
                SuperClass json = gson.fromJson(result, SuperClass.class);

                List<Data> list = json.getData();

                System.out.println("集合+++++++" + list);
            }

        };

        asyncTask.execute(new Void[] {});

    }

}

posted on 2016-04-12 16:48  天空很大,我们很小  阅读(263)  评论(0编辑  收藏  举报