为AsyncTask

时间:2018-08-08 07:11:27

标签: java android json asynchronous android-asynctask

我正在开发一个具有很多远程JSON调用的应用程序,以获取数据并在应用程序中实现。

当前,我正在使用此功能从URL获取JSON数据并对其进行解析。

但是不幸的是,它会冻结应用程序,直到下载JSON文件为止。

在Google上进行搜索,发现AsyncTask可以解决此问题。

我刚刚开始进行android应用程序开发。我尝试过但失败了。

你们能帮我实现AsyncTask的此功能吗?

public class JSONParser {

String charset = "UTF-8";
HttpURLConnection conn;
DataOutputStream wr;
StringBuilder result;
URL urlObj;
JSONObject jObj = null;
JSONArray jAry = null;
StringBuilder sbParams;
String paramsString;

public JSONObject makeHttpRequest(String url, String method, HashMap<String, String> params) {

    sbParams = new StringBuilder();
    int i = 0;
    for (String key : params.keySet()) {
        try {
            if (i != 0) {
                sbParams.append("&");
            }
            sbParams.append(key).append("=")
                    .append(URLEncoder.encode(params.get(key), charset));

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        i++;
    }

    if (method.equals("POST")) {
        try {
            urlObj = new URL(url);
            conn = (HttpURLConnection) urlObj.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Accept-Charset", charset);
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(15000);
            conn.connect();
            paramsString = sbParams.toString();
            wr = new DataOutputStream(conn.getOutputStream());
            wr.writeBytes(paramsString);
            wr.flush();
            wr.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    } else if (method.equals("GET")) {
        if (sbParams.length() != 0) {
            url += "?" + sbParams.toString();
        }

        Log.d("URL",url);
        try {
            urlObj = new URL(url);
            conn = (HttpURLConnection) urlObj.openConnection();
            conn.setDoOutput(false);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept-Charset", charset);
            conn.setConnectTimeout(15000);
            conn.connect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    try {
        InputStream in = new BufferedInputStream(conn.getInputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        result = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            result.append(line);
        }

        Log.d("JSON Parser", "result: " + result.toString());

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

    conn.disconnect();

    try {
        jObj = new JSONObject(result.toString());
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    return jObj;
}}

这是我进行json调用的方式:

JSONParser jsonParser = new JSONParser();
JSONObject json = jsonParser.makeHttpRequest("https://url", "GET", parametters);

1 个答案:

答案 0 :(得分:1)

如果您想使用AsyncTask进行此操作,这是一个很好的开始:

public class JsonParser extends AsyncTask<Void, Void, JSONObject> {

    public interface ParserListener {
        void onSuccess(JSONObject result);
        void onFailure();
    }

    private ParserListener listener;    
    private HashMap<String, String> params;
    private String method;
    private String url;
    String charset = "UTF-8";
    HttpURLConnection conn;
    DataOutputStream wr;
    StringBuilder result;
    URL urlObj;
    JSONObject jObj = null;
    JSONArray jAry = null;
    StringBuilder sbParams;
    String paramsString;

    public JsonParser(String url, String method, HashMap<String, String> params) {
        this.url = url;
        this.method = method;
        this.params = params;
    }

    public void setListener(ParserListener listener) {
        this.listener = listener;
    }

    @Override
    protected JSONObject doInBackground(Void... voids) {
        sbParams = new StringBuilder();
        int i = 0;
        for (String key : params.keySet()) {
            try {
                if (i != 0) {
                    sbParams.append("&");
                }
                sbParams.append(key).append("=")
                        .append(URLEncoder.encode(params.get(key), charset));

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            i++;
        }

        if (method.equals("POST")) {
            try {
                urlObj = new URL(url);
                conn = (HttpURLConnection) urlObj.openConnection();
                conn.setDoOutput(true);
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Accept-Charset", charset);
                conn.setReadTimeout(10000);
                conn.setConnectTimeout(15000);
                conn.connect();
                paramsString = sbParams.toString();
                wr = new DataOutputStream(conn.getOutputStream());
                wr.writeBytes(paramsString);
                wr.flush();
                wr.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (method.equals("GET")) {
            if (sbParams.length() != 0) {
                url += "?" + sbParams.toString();
            }

            Log.d("URL",url);
            try {
                urlObj = new URL(url);
                conn = (HttpURLConnection) urlObj.openConnection();
                conn.setDoOutput(false);
                conn.setRequestMethod("GET");
                conn.setRequestProperty("Accept-Charset", charset);
                conn.setConnectTimeout(15000);
                conn.connect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            InputStream in = new BufferedInputStream(conn.getInputStream());
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            result = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }

            Log.d("JSON Parser", "result: " + result.toString());

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

        conn.disconnect();

        try {
            jObj = new JSONObject(result.toString());
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        return jObj;
    }

    @Override
    protected void onPostExecute(JSONObject jsonObject) {
        /* executed on main thread */
        if (listener != null) {
            if (jsonObject != null) {
                listener.onSuccess(jsonObject);
            } else {
                listener.onFailure();
            }
        }
    }
}

并使用它:

JsonParser parser = new JsonParser("https://url", "GET", parameters);
parser.setListener(new JsonParser.ParserListener() {
      @Override
       public void onSuccess(JSONObject result) {
            /* delivered result */
        }

        @Override
        public void onFailure() {
                /* delivered failure */
        }
        });
parser.execute();

代码可以改进,并且正如注释中所指出的,有更好的方法可以做到这一点。 AsyncTask在学习阶段仍然很有趣。