AsyncTask下载JSON

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AsyncTask下载JSON相关的知识,希望对你有一定的参考价值。

public class HttpUtils {

    // 从网络url上下载字符串
    public static String getHttpStr(String url) {
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse response = httpClient.execute(httpGet);// 发起http请求
            if (response.getStatusLine().getStatusCode() == 200) {
                // 请求成功
                HttpEntity entity = response.getEntity();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();// 字节数组输出流
                InputStream is = entity.getContent(); // 获取输入流
                byte[] buffer = new byte[1024];
                int ret;
                while (true) {
                    ret = is.read(buffer);
                    if (ret < 0) {
                        break;
                    }
                    baos.write(buffer, 0, ret); // 读多少、写多少
                }
                return baos.toString();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
public class JSONUtils {

    // 读入json字符串并返回List<String>城市列表
    // 格式为 {"citys":["北京","上海","山东","河北","广东"]}
    public static List<String> parseCityJSONStr(String jsonStr) {
        try {
            List<String> listCity = new ArrayList<String>();
            // JSON字符串中{}表示JSONObject
            // 这里创建JSONObject对象
            JSONObject jsonObject = new JSONObject(jsonStr);
            // 根据json对象中冒号前的内容(key)获取冒号后的内容(value)
            // 后面的内容是JSON数组(JSONArray)
            JSONArray jsonArr = (JSONArray) jsonObject.get("citys");
            // 遍历JSON数组,并把一个一个元素放入List<String>中
            for (int i = 0; i < jsonArr.length(); i++) {
                // 根据下标获取jsonArr中的元素
                String city = (String) jsonArr.get(i);
                listCity.add(city);
            }
            return listCity;
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }
}
public class MyTask extends AsyncTask<String, Void, List<String>> {

    private Spinner spinner;

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

    @Override
    protected List<String> doInBackground(String... params) {
        String jsonStr = HttpUtils.getHttpStr(params[0]);
        List<String> citys = JSONUtils.parseCityJSONStr(jsonStr);
        for (String city : citys) {
            Log.i("MyTask", city);
        }
        return citys;
    }

    @Override
    protected void onPostExecute(List<String> result) {
        super.onPostExecute(result);
    }

}
public class MainActivity extends Activity {

    private Spinner spinner;
    private String url = "http://10.16.154.26:8080/Web_Product/CityServlet?type=json";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        spinner = (Spinner) findViewById(R.id.spinner);
        MyTask task = new MyTask();
        task.execute(url);
        List<String> result;
        try {
            result = task.get();
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1,
                    result);
            spinner.setAdapter(adapter);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

 

以上是关于AsyncTask下载JSON的主要内容,如果未能解决你的问题,请参考以下文章

使用 AsyncTask 从 JSON 中获取数据

从Asynctask ONPostExecute调用片段方法

如何从选项卡片段中的 AsyncTask Resftful WS 加载批量数据

AsyncTask下载JSON

如何在切换片段时停止 AsyncTask?

片段中的 Asynctask 未到达 onPostExecute