在“Android异步Http客户端库”中获取JSON

时间:2014-01-12 09:47:26

标签: android json asynchronous

我最近转移到Android Asynchronous Http Client Library以便更快地移动数据。

我想从旧状态和新状态移动我的代码。以下是我以前获取数据的方式:

public class loadSomeStuff extends AsyncTask<String, Integer, String> {
        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub
            InputStream isr = null;
            String result = "";
            String url;
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httpost;
            HttpResponse resposne;
            HttpEntity entity;
            BufferedReader reader;
            StringBuilder sb;
            String line = null;

            try {
                url = "Secret";
                httpost = new HttpPost(url);
                resposne = httpclient.execute(httpost);
                entity = resposne.getEntity();
                isr = entity.getContent();
                reader = new BufferedReader(
                        new InputStreamReader(isr, "UTF-8"), 8);
                sb = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                isr.close();
                result = sb.toString();

                JSONArray jArray = new JSONArray(result);
                for (int i = 0; i < jArray.length(); i++) {
                    JSONObject json = jArray.getJSONObject(i);
                    //filldatabase///
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        }

现在我该怎么做才能使用这个库?谢谢!

2 个答案:

答案 0 :(得分:1)

请按照文档中的示例进行操作:

AsyncHttpClient client = new AsyncHttpClient();
client.get("http://your/url/here/", new AsyncHttpResponseHandler() {
    @Override
    public void onSuccess(String response) {
        JSONArray jarr = new JSONArray(response);
        for(int i = 0; i < jarr.length(); ++i) {
            JSONObject jobj = jarr.getJSONObject(i);
            // do your things...
        }
    }
});

您不再需要AsyncTask,请将代码替换为new loadSomeStuff().start()并删除loadSomeStuff类。

答案 1 :(得分:0)

  1. 小心使用此库,因为您无法在AsyncTask中使用它。我猜它已经使用了这个帖子。

  2. 如果JSON上没有任何内容,那可能是因为数据尚未返回。因此,在执行解析作业之前,必须等待util返回数据。


  3. 我有使用此库的经验。我认为这个库适用于某些回调并不重要的情况。例如,您不必等待数据返回并解析它。

    也许你可以尝试这个(不推荐):

    AsyncHttpClient client = new AsyncHttpClient();
    client.get("url", new AsyncHttpResponseHandler() {
    @Override
    public void onSuccess(String response) {
        //Check the data return
        while(response.length==0)
        {
            Thread.sleep(100);// Waiting for data return
        }
        //Parsing data
        JSONArray jarr = new JSONArray(response);
        for(int i = 0; i < jarr.length(); ++i) {
            JSONObject jobj = jarr.getJSONObject(i);
            ...
        }
    }
    

    });


    以下是您旧代码的一些建议:) *分隔http帖子和JSON。把它们都放在一个班级里。 这样做可以使您的代码更简短,也可以重复使用。这就是我的意思:

    public class Util {
    
    public String doPost() {
        InputStream isr = null;
        String result = "";
        String url;
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httpost;
        HttpResponse resposne;
        HttpEntity entity;
        BufferedReader reader;
        StringBuilder sb;
        String line = null;
    
        try {
               url = "Secret";
               httpost = new HttpPost(url);
               resposne = httpclient.execute(httpost);
               entity = resposne.getEntity();
               isr = entity.getContent();
               reader = new BufferedReader(
                        new InputStreamReader(isr, "UTF-8"), 8);
                        sb = new StringBuilder();
                        while ((line = reader.readLine()) != null) {
                            sb.append(line + "\n");
                        }
                        isr.close();
                        result = sb.toString();
    
                        //Remove JSON
                    } catch (Exception e) {
                        e.printStackTrace();
        }
        return result;
    }
    
    public parsindData(String result)
    {
        JSONArray jArray = new JSONArray(result);
        for (int i = 0; i < jArray.length(); i++) {
        JSONObject json = jArray.getJSONObject(i);
        //filldatabase///
    }
    

    }

    将它们用作对象:

    // AsyncTask doInBackground

    Util util=new Util();
    String getCallBack=util.doPost();
    if(getCallBack.length!=0)
    {
        util.parsingData(getCallBack);
    }