是否有进行异步HTTP请求在Android中公认的最佳实践?HTTP、Android

2023-09-12 10:53:29 作者:蜗牛你慢点

我见过的任何数量的例子,他们似乎都以不同的解决这个问题。基本上,我只是想最简单的方法,使不会锁定主线程,并取消请求。

I've seen any number of examples and they all seem to solve this problem differently. Basically I just want the simplest way to make the request that won't lock the main thread and is cancelable.

它也没有帮助,我们有(至少)2 HTTP库的,java.net选择。*(如HttpURLConnection类),并org.apache.http。*。

It also doesn't help that we have (at least) 2 HTTP libraries to choose from, java.net.* (such as HttpURLConnection) and org.apache.http.*.

是否有最好的做法是什么共识?

Is there any consensus on what the best practice is?

推荐答案

而Android 1.5 SDK引入了一个新的类,的 AsyncTask的设计,使在后台线程上运行的任务和沟通的结果到UI线程稍微简单一些。在 Android开发者博客给出了如何使用它的基本思想给出一个例子:

The Android 1.5 SDK introduced a new class, AsyncTask designed to make running tasks on a background thread and communicating a result to the UI thread a little simpler. An example given in the Android Developers Blog gives the basic idea on how to use it:

public void onClick(View v) {
   new DownloadImageTask().execute("https://m.xsw88.com/allimgs/daicuo/20230912/6490.png");
}

private class DownloadImageTask extends AsyncTask {
   protected Bitmap doInBackground(String... urls) {
      return loadImageFromNetwork(urls[0]);
   }

   protected void onPostExecute(Bitmap result) {
      mImageView.setImageBitmap(result);
   }
}

doInBackgroundThread 方法被调用一个单独的线程(通过汇集线程管理的ExecutorService ),其结果是传达给 onPostExecute 方法,它是运行在UI线程上。您可以拨打取消(布尔mayInterruptIfRunning)的AsyncTask 子类来取消正在运行的任务。

The doInBackgroundThread method is called on a separate thread (managed by a thread pooled ExecutorService) and the result is communicated to the onPostExecute method which is run on the UI thread. You can call cancel(boolean mayInterruptIfRunning) on your AsyncTask subclass to cancel a running task.

至于使用 java.net org.apache.http 进行网络访问库,它是由您。我已经找到了 java.net 图书馆安静愉快的使用的时候只是想发出 GET 和阅读结果。该 org.apache.http 库将允许你做几乎任何你想与 HTTP 什么,但他们可以是一个一点比较难使用,我发现他们不执行,以及(在Android)简单 GET 的要求。

As for using the java.net or org.apache.http libraries for network access, it's up to you. I've found the java.net libraries to be quiet pleasant to use when simply trying to issue a GET and read the result. The org.apache.http libraries will allow you to do almost anything you want with HTTP, but they can be a little more difficult to use and I found them not to perform as well (on Android) for simple GET requests.