我应该依靠传统方法来请求 GET/POST 还是其他库 (Android)

Shall I rely on traditional method for GET/POST request or other libraries (Android)

我是 android 开发的初学者,正在开发一个应用程序。我想知道我应该使用传统方法进行 GET/POST 请求(即 URLConnection,HttpClient)还是应该使用第三方库,例如 OkHttp 毕加索 。我应该使用哪种方法请提供指导。谢谢

你用传统方法 GET/POST。我正在给你举个例子。 为此,您必须创建一个使用 AsyncTask

扩展的 class
public class getData extends AsyncTask<String, String, String> {

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

    @Override
    protected String doInBackground(String... params) {
        String response = null;
        try {
            URL url = new URL("Write you url here");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");

// 在这里你可以写你的方法 - GET 或 POST

            InputStream in = new BufferedInputStream(conn.getInputStream());
            response = IOUtils.toString(in, "UTF-8");
            System.out.println(response);

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

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        if (result != null) {
            try {
                JSONArray array = new JSONArray(result);
                for (int i = 0; i < array.length(); i++) {
                    JSONObject c = array.getJSONObject(i);
                    String id = c.getString("tag");
                    Log.e("", "TAG : - " + id);
                    Category category = new Category(id);
                    albumsList.add(category);
                }
            } catch (Exception e) {
                Log.e("", "Home Exception : " + e.toString());
            }
        }
        pDialog.dismiss();

        getActivity().runOnUiThread(new Runnable() {
            public void run() {
                getList_category().setAdapter(new MenuAdapter(getActivity(), albumsList, 0));
            }
        });
    }
}

您必须在 onCreate 方法中或任何您想调用它的地方调用它 class。

new getData().execute();

如上所说。

快乐的代码和快乐的帮助....

不要使用 HttpClient,它已在 Marshmallow 中弃用并删除。

URLConnection 很好,但它对阅读响应没有任何帮助,即您必须自己阅读流,这很快就会很痛苦。此外,您还必须确保您的调用是异步的,这意味着要添加越来越多的代码……并不完美。

因此,您只剩下 OkHttp 或 Volley。这些是 "low level" 个网络库,它们只帮助您发出请求和读取响应。不过他们做得很好,请继续阅读他们的文档。

除此之外,您还可以将其他库用于更具体的用途。如果您需要对格式良好的 REST 进行一些调用 API,我建议使用基于 OkHttp 的 Retrofit。

如果您需要检索图像,Picasso 非常适合(并且还利用了 OkHttp)。我想 "market" 上的其他人也不错(Glide、Fresco 等),但我没用过。

查找一些比较所有这些库的性能和易用性的文章。你永远不应该在没有最低评估的情况下添加库。

最后... https://github.com/futurice/android-best-practices

干杯。