在 Android 上调用返回 JSON 响应的 HTTP Web API 调用的

What is the most efficient way on Android to call HTTP Web API calls that return a JSON response?(在 Android 上调用返回 JSON 响应的 HTTP Web API 调用的最有效方法是什么?)

本文介绍了在 Android 上调用返回 JSON 响应的 HTTP Web API 调用的最有效方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是完美主义者,我已经让网络 API 调用与 Google Places API 一起正常工作(仅作为示例),但我觉得它有时很慢,或者我可能做得不对.一些博客说我应该使用 AndroidHttpClient,但我不是,应该吗?

I'm the perfectionist type, I already got web API calls working fine with Google Places API (just as an example), but I feel it's sometimes slow or maybe I'm not doing it right. Some blogs are saying I should use AndroidHttpClient, but I'm not, should I ?

Web API 调用我使用返回 json 并且我不在 UI 线程上运行它们,因此使用 AsyncTask(AsyncTask 是在后台线程上运行的最有效方法还是我应该使用其他方法?)

The web API calls i'm using return json and I don't run them on the UI thread, hence using AsyncTask (is AsyncTask the most efficient way to run on background thread or should I use something else ?)

请查看我的代码并告诉我如何才能更有效

Please see my code and tell me how could it be more efficient in anyway

public static class NearbySearchRequest extends AsyncTask<String, Void, JSONObject>
{
    Exception mException = null;

    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();
        this.mException = null;
    }

    @Override
    protected JSONObject doInBackground(String... params)
    {
        StringBuilder urlString = new StringBuilder();
        urlString.append("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
        urlString.append("key=").append(Constants.GOOGLE_SIMPLE_API_KEY);
        urlString.append("&location=").append(params[0]);
        urlString.append("&sensor=").append("true");
        urlString.append("&language=").append("en-GB");
        urlString.append("&name=").append(params[1]);
        urlString.append("&rankby=").append("distance");

        LogHelper.Log(urlString.toString());

        HttpURLConnection urlConnection = null;
        URL url = null;
        JSONObject object = null;

        try
        {
            url = new URL(urlString.toString());
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.connect();
            InputStream inStream = null;
            inStream = urlConnection.getInputStream();
            BufferedReader bReader = new BufferedReader(new InputStreamReader(inStream));
            String temp, response = "";
            while ((temp = bReader.readLine()) != null)
                response += temp;
            bReader.close();
            inStream.close();
            urlConnection.disconnect();
            object = (JSONObject) new JSONTokener(response).nextValue();
        }
        catch (Exception e)
        {
            this.mException = e;
        }

        return (object);
    }

    @Override
    protected void onPostExecute(JSONObject result)
    {
        super.onPostExecute(result);

        if (this.mException != null)
            ErrorHelper.report(this.mException, "Error # NearbySearchRequest");
    }
}

推荐答案

您使用的 Http 引擎似乎是最佳选择.实际上,任何其他第 3 方引擎都基于 Apache,或者基于 HttpUrlConnection.我更喜欢使用 Spring for Android,因为该 API 提供了对 Http 引擎的抽象,而您却没有真的需要关心如何基于 API 级别使用什么 API.或者你可以使用 Volley——一个非常时尚的库.

The Http engine you're using seems the best choice. Actually any other 3-rd party engines are based either on Apache, either on HttpUrlConnection. I prefer to use Spring for Android as that API provide an abstraction over Http Engine and you don't really need to care how about what API to use based on API level. Or you can use Volley - a very fashionable library.

不过我会接触你的一些代码:

I would touch however some of your code:

  1. 如果在读取流时出现异常怎么办?然后流保持打开状态,连接也保持打开状态.所以我建议在 finally 块中关闭流和连接,无论您是否遇到异常:

  1. What if there is an exception while reading the stream? Then the stream remains open and also the connection. So I would suggest to have a finally block where the streams and connection is closed no matter if you get an exception or not:

HttpURLConnection urlConnection = null;
URL url = null;
JSONObject object = null;
InputStream inStream = null;
try {
    url = new URL(urlString.toString());
    urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setRequestMethod("GET");
    urlConnection.setDoOutput(true);
    urlConnection.setDoInput(true);
    urlConnection.connect();
    inStream = urlConnection.getInputStream();
    BufferedReader bReader = new BufferedReader(new InputStreamReader(inStream));
    String temp, response = "";
    while ((temp = bReader.readLine()) != null) {
        response += temp;
    }
    object = (JSONObject) new JSONTokener(response).nextValue();
} catch (Exception e) {
    this.mException = e;
} finally {
    if (inStream != null) {
        try {
            // this will close the bReader as well
            inStream.close();
        } catch (IOException ignored) {
        }
    }
    if (urlConnection != null) {
        urlConnection.disconnect();
    }
}

  • JSON 解析:您使用的是 Android 标准的 JSON 解析方式,但这并不是最快和最容易使用的方式.GSON 和 Jackson 更好用.为了比较 JSON 解析器,我会去杰克逊.这是关于此比较的另一个 SO 主题.

  • JSON parsing: you're using the Android standard way of parsing JSON, but that's not the fastest and easiest to work with. GSON and Jackson are better to use. To make a comparison when it comes for JSON parsers, I would go for Jackson. Here's another SO topic on this comparison.

    不要像这样连接字符串,因为连接字符串每次都会创建另一个字符串.改用 StringBuilder.

    Don't concatenate strings like that as concatenating strings will create each time another string. Use a StringBuilder instead.

    异常处理(这在所有编程论坛中都是一个长期争论的话题).首先,您必须记录它(使用 Log 类不是 System.out.printXXX).然后,您需要通知用户:要么敬酒,要么显示标签或通知.该决定取决于用户案例以及您拨打的电话的相关性.

    Exception handling (this is anyway a long-debate subject in all programming forums). First of all you have to log it (Use Log class not System.out.printXXX). Then you need to either inform the user: either you toast a message, either you show a label or notification. The decision depends on the user case and how relevant is the call you're making.

    这些是我在你的代码中看到的主题.

    These are the topics I see in you code.

    编辑我意识到我没有回答这个问题:AsyncTask 是在后台线程上运行的最有效方法还是我应该使用其他方法?

    EDIT I realize I didn't answer this: is AsyncTask the most efficient way to run on background thread or should I use something else?

    我给出的简短回答是:如果您应该执行一个短时间的请求,那么 AsyncTask 是完美的.但是,如果您需要获取一些数据并显示它——但又不想担心屏幕旋转时是否再次下载等等,我强烈建议使用 AsyncTaskLoaderLoaders 一般.

    The short answer I would give is: if you're supposed to perform a short time lived request, then AsyncTask is perfect. However, if you need to get some data and display it - but you don't want to worry about whether to download again if the screen is rotated and so on, I would strongly recommend using an AsyncTaskLoader and Loaders in general.

    如果您需要下载一些大数据,那么您可以使用 IntentService 或者,对于重量级操作,DownloadManager.

    If you need to download some big data, then either you use an IntentService or, for heavy-weight operations, DownloadManager.

    享受编码!

    这篇关于在 Android 上调用返回 JSON 响应的 HTTP Web API 调用的最有效方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

  • 本文标题为:在 Android 上调用返回 JSON 响应的 HTTP Web API 调用的

    基础教程推荐