[关闭]
@cxm-2016 2017-01-14T14:54:52.000000Z 字数 9497 阅读 3441

OkHttp3 (三)——创建与执行网络请求

OkHttp3

版本:3
作者:陈小默
声明:禁止商业,禁止转载

发布于:作业部落简书CSDN



请求

在OkHttp中,一般的请求方式为:

  1. fun main(args: Array<String>) {
  2. val client = OkHttpClient()
  3. val request = Request.Builder()
  4. .url(URL)
  5. .build()
  6. val call = client.newCall(request)
  7. val response = call.execute()
  8. if (response.isSuccessful) {
  9. // 请求成功
  10. }
  11. response.close()
  12. }

当我们使用newCall()函数的时候,OkHttp就会通过传入的请求对象生成一个可执行的Call对象。当我们执行Call对象的execute()方法的时候,就会开始执行网络请求,并且得到响应对象。需要注意的是,此方法的执行方式为同步阻塞的,也就是说该线程会被暂停在这里直到接收到服务端的响应或者发生错误从而继续执行。

异步请求

在有些不能使用直接请求的场景下,比如Android或者某些不希望进程被阻塞的应用,我们就需要通过异步的方式来执行请求,并且在合适的时候回调。写法如下:

  1. fun main(args: Array<String>) {
  2. val client = OkHttpClient()
  3. val request = Request.Builder()
  4. .url(URL)
  5. .build()
  6. val call = client.newCall(request)
  7. call.enqueue(object : Callback {
  8. override fun onFailure(call: Call, e: IOException) {
  9. // 请求过程中出现错误时回调
  10. e.printStackTrace()
  11. }
  12. override fun onResponse(call: Call, response: Response) {
  13. // 请求成功时回调
  14. }
  15. })
  16. }

enqueue是一个异步请求方法,其中传入的参数Callback是请求回调的接口。注意:当我们使用异步请求的时候,也是需要关闭Response对象的。

在使用异步请求的时候,RealCall的执行流程方法如下:

  1. @Override protected void execute() {
  2. boolean signalledCallback = false;
  3. try {
  4. Response response = getResponseWithInterceptorChain();
  5. if (retryAndFollowUpInterceptor.isCanceled()) {
  6. signalledCallback = true;
  7. responseCallback.onFailure(RealCall.this, new IOException("Canceled"));
  8. } else {
  9. signalledCallback = true;
  10. responseCallback.onResponse(RealCall.this, response);
  11. }
  12. } catch (IOException e) {
  13. if (signalledCallback) {
  14. // Do not signal the callback twice!
  15. Platform.get().log(INFO, "Callback failure for " + toLoggableString(), e);
  16. } else {
  17. responseCallback.onFailure(RealCall.this, e);
  18. }
  19. } finally {
  20. client.dispatcher().finished(this);
  21. }
  22. }

通过上面的函数,我们可以看到其调用规律:当请求被取消时,回调onFailure,否则回调onResponse并且将获取的response对象传入。这里需要注意的是,response交给调用者之后,OkHttp并没有对其进行任何附带的处理,比如关闭。这就要求调用者必须在回调方法中关闭Response对象,就像这样:

  1. call.enqueue(object : Callback {
  2. override fun onFailure(call: Call, e: IOException) {
  3. // 请求过程中出现错误时回调
  4. e.printStackTrace()
  5. }
  6. override fun onResponse(call: Call, response: Response) {
  7. // 请求成功时回调
  8. //无论任何情况都要关闭该对象
  9. response.close()
  10. }
  11. })

处理文本数据

发出请求后,服务器会返回给客户端一些数据,当然,在某些场景下,你可能仅仅会受到服务器的响应头信息而没有任何数据。

response.body()函数能够获取到服务器返回用数据。

在其中,封装了一个名叫string的函数,这个函数能够将接收到的数据重新解码为字符串并返回。在传递文本数据时非常有用。

  1. call.enqueue(object : Callback {
  2. override fun onFailure(call: Call, e: IOException) {
  3. e.printStackTrace()
  4. }
  5. override fun onResponse(call: Call, response: Response) {
  6. val body = response.body()
  7. val string = body.string()
  8. println(string)
  9. // {"success":true,"message":"hello","data":"服务器接收到了客户端的来信"}
  10. response.close()
  11. }
  12. })

处理字节数组

除了文本信息,我们还可能收到小型文件数据。在数据比较小的情况下,我们可以先以字节数据的形式保存在内存中,然后再将其一次性写入文件。

  1. call.enqueue(object : Callback {
  2. override fun onFailure(call: Call, e: IOException) {
  3. e.printStackTrace()
  4. }
  5. override fun onResponse(call: Call, response: Response) {
  6. val body = response.body()
  7. val bytes = body.bytes()
  8. mImageFile.writeBytes(bytes)
  9. response.close()
  10. }
  11. })

处理字节流

当我们需要下载的文件比较大时,将所有数据保存在字节数组中的方法就已经不再适用了,那么我们需要通过流的形式,将数据保存在文件中。

  1. call.enqueue(object : Callback {
  2. override fun onFailure(call: Call, e: IOException) {
  3. e.printStackTrace()
  4. }
  5. override fun onResponse(call: Call, response: Response) {
  6. val body = response.body()
  7. val head = response.header("Content-Disposition")
  8. //attachment;filename=One+More+Chance.mp4
  9. val oName = head.substring(head.indexOf("=") + 1, head.length)
  10. val filename = URLDecoder.decode(oName, "utf-8")
  11. //One More Chance.mp4
  12. val fOut = File(LOCAL_PATH, filename).outputStream()
  13. val input = body.byteStream()
  14. val bytes = ByteArray(64 * 1024)
  15. var len = 0
  16. do {
  17. fOut.write(bytes, 0, len)
  18. len = input.read(bytes)
  19. } while (len > 0)
  20. fOut.close()
  21. input.close()
  22. response.close()
  23. }
  24. })

带进度下载文件

如果我们需要在下载过程中获取到下载的进度,我们就需要对下载过程进行封装。

  1. fun download(call: Call, dir: String,
  2. onStart: (filename: String) -> Unit,
  3. progress: (current: Long, max: Long, speed: Long) -> Unit,
  4. onError: (Exception) -> Unit,
  5. onCompleted: () -> Unit) {
  6. call.enqueue(object : Callback {
  7. override fun onFailure(call: Call, e: IOException) {
  8. onError(e)
  9. }
  10. override fun onResponse(call: Call, response: Response) {
  11. var out: OutputStream? = null
  12. var input: InputStream? = null
  13. try {
  14. //--------获取下载文件的文件名,并判断本地是否有重名文件,如果有就在文件名后加上数字
  15. val head = response.header("Content-Disposition")
  16. val oName = head.substring(head.indexOf("=") + 1, head.length)
  17. var filename = URLDecoder.decode(oName, "utf-8")
  18. val left = filename.substring(0, filename.lastIndexOf("."))
  19. val right = filename.substring(filename.lastIndexOf("."), filename.length)
  20. var file = File(dir, filename)
  21. var index = 1
  22. while (file.exists()) {
  23. filename = "$left(${index++})$right"
  24. file = File(dir, filename)
  25. }
  26. //--------将当前文件名回调
  27. onStart(filename)
  28. //--------获取输入输出流
  29. out = File(dir, filename).outputStream()
  30. input = response.body().byteStream()
  31. //--------准备下载用到的缓冲区
  32. val bytes = ByteArray(512 * 1024)
  33. var len = 0
  34. var current = 0L
  35. val max = response.body().contentLength()
  36. //--------用于计算下载速度
  37. var timer = System.currentTimeMillis()
  38. var speed = 0L
  39. do {
  40. current += len
  41. speed += len
  42. //------时间每超过一秒就回调一次下载进度
  43. val currentTimer = System.currentTimeMillis()
  44. if (currentTimer - timer > 1000) {
  45. progress(current, max, speed)
  46. timer = currentTimer
  47. speed = 0L
  48. }
  49. out.write(bytes, 0, len)
  50. len = input.read(bytes)
  51. } while (len > 0)
  52. } catch (e: Exception) {
  53. onError(e)
  54. } finally {
  55. if (input != null)
  56. try {
  57. input.close()
  58. } catch (e: IOException) {
  59. }
  60. if (out != null)
  61. try {
  62. out.close()
  63. } catch (e: IOException) {
  64. }
  65. response.close()
  66. }
  67. onCompleted()
  68. }
  69. })
  70. }

上面的函数额外部分有:

文件命名:
将重复文件以编号形式重新命名。

定时回调:
这里采用比较时间的方式来判断是否应该回调。这是一种比较粗糙的计时方式,但是可以满足绝大部分的应用场景。如果对时间要求比较高的话,应该另外开启一个用于计时的线程。

接下来我们看一下如何使用:

  1. fun main(args: Array<String>) {
  2. val client = OkHttpClient()
  3. val request = Request.Builder()
  4. .url(RESOURCE)
  5. .build()
  6. val call = client.newCall(request)
  7. download(call, LOCAL_PATH,
  8. ::println,
  9. { current, max, speed ->
  10. println("当前下载进度: ${current * 100 / max}% 下载速度${speed / 1024}KB/s")
  11. },
  12. Exception::printStackTrace,
  13. {
  14. println("下载完成")
  15. })
  16. }
One More Chance(2).mp4
当前下载进度: 1%  下载速度363KB/s
当前下载进度: 2%  下载速度347KB/s
当前下载进度: 4%  下载速度540KB/s
当前下载进度: 7%  下载速度580KB/s
当前下载进度: 8%  下载速度458KB/s
当前下载进度: 10%  下载速度455KB/s
当前下载进度: 12%  下载速度510KB/s
...
当前下载进度: 97%  下载速度386KB/s
当前下载进度: 99%  下载速度453KB/s
下载完成

BufferedSource

由于OkHttp封装了okio,所以可以将响应数据通过BufferedSource的形式返回。

  1. val buffer = response.body().source()

BufferedSource中的其他功能不再赘述。这里只介绍其中一种用法,就是跳过一定长度的数据,接下来从服务器请求并截取字符串:

  1. fun main(args: Array<String>) {
  2. val client = OkHttpClient()
  3. val request = Request.Builder()
  4. .url("$ECHO?message=hello")
  5. .build()
  6. val call = client.newCall(request)
  7. val response = call.execute()
  8. val buffer = response.body().source()
  9. buffer.skip(20) //跳过20个字节
  10. val string = buffer.readString(31, Charset.forName("UTF-8")) //向后读取31个字节的数据
  11. println(string)
  12. response.close()
  13. }

打印结果为:

sage":"hello","data":"服务器

可以看到前面确实是少了一部分数据的。该用法的使用场景通常为文件的断点续传。在支持断点续传的站点,我们是可以直接通过请求头来向站点请求某一段的数据。但是对于不支持断点续传的站点,我们就可以通过BufferedSource的skip在本地跳过一段数据。并且在BufferedSource的read*方法中通常都有一个指定长度的重载,这么一来,一个断点续传的功能就能轻易实现了。

Android中的异步请求

如果你在Android应用中直接使用上述代码进行异步请求,并且在回调方法中操作了UI,那么你的程序就会抛出异常,并且告诉你不能在非UI线程中操作UI。这是因为OkHttp对于异步的处理仅仅是开启了一个线程,并且在线程中处理响应。OkHttp是一个面向于Java应用而不是特定平台(Android)的框架,那么它就无法在其中使用Android独有的Handler机制。于是,当我们需要在Android中进行网络请求并且需要在回调用操作UI的话,就需要自行封装一套带Handler的回调。

接下来我们将上面带进度下载的例子修改为Android适用的版本:

  1. class DownloadUtils(url: String,
  2. progress: (current: Long, max: Long, speed: Long) -> Unit,
  3. onError: (Exception) -> Unit,
  4. onCompleted: (result: ByteArray) -> Unit) {
  5. private val PROGRESS = 1
  6. private val ERROR = 2
  7. private val COMPLETED = 3
  8. private val TAG_CURRENT = "current"
  9. private val TAG_MAX = "max"
  10. private val TAG_SPEED = "speed"
  11. private val client = OkHttpClient()
  12. private val handler = object : Handler() {
  13. override fun handleMessage(msg: Message) {
  14. when (msg.arg1) {
  15. PROGRESS -> {
  16. val current = msg.data.getLong(TAG_CURRENT, 0)
  17. val max = msg.data.getLong(TAG_MAX, 1)
  18. val speed = msg.data.getLong(TAG_SPEED, 0)
  19. progress(current, max, speed)
  20. }
  21. ERROR -> {
  22. val error = msg.obj as Exception
  23. onError(error)
  24. }
  25. COMPLETED -> {
  26. val result = msg.obj as ByteArray
  27. onCompleted(result)
  28. }
  29. else -> super.handleMessage(msg)
  30. }
  31. }
  32. }
  33. private val call: okhttp3.Call
  34. init {
  35. val request = Request.Builder()
  36. .url(url)
  37. .build()
  38. call = client.newCall(request)
  39. }
  40. var isCancel = false
  41. private set
  42. fun start() {
  43. call.enqueue(object : okhttp3.Callback {
  44. override fun onFailure(call: okhttp3.Call, e: IOException) {
  45. val msg = handler.obtainMessage()
  46. msg.arg1 = ERROR
  47. msg.obj = e
  48. handler.sendMessage(msg)
  49. }
  50. override fun onResponse(call: okhttp3.Call, response: okhttp3.Response) {
  51. var out: OutputStream? = null
  52. var input: InputStream? = null
  53. try {
  54. out = ByteArrayOutputStream()
  55. input = response.body().byteStream()
  56. val bytes = ByteArray(8 * 1024)
  57. var len = 0
  58. var current = 0L
  59. val max = response.body().contentLength()
  60. var timer = System.currentTimeMillis()
  61. var speed = 0L
  62. do {
  63. current += len
  64. speed += len
  65. val currentTimer = System.currentTimeMillis()
  66. if (currentTimer - timer > 1000) {
  67. val msg = handler.obtainMessage()
  68. msg.arg1 = PROGRESS
  69. msg.data.putLong(TAG_CURRENT, current)
  70. msg.data.putLong(TAG_MAX, max)
  71. msg.data.putLong(TAG_SPEED, speed)
  72. handler.sendMessage(msg)
  73. timer = currentTimer
  74. speed = 0L
  75. }
  76. out.write(bytes, 0, len)
  77. len = input.read(bytes)
  78. } while (len > 0 && !isCancel)
  79. if (isCancel)
  80. throw IOException("Cancel")
  81. val msg = handler.obtainMessage()
  82. msg.arg1 = COMPLETED
  83. msg.obj = out.toByteArray()
  84. handler.sendMessage(msg)
  85. } catch (e: IOException) {
  86. onFailure(call, e)
  87. } finally {
  88. if (input != null)
  89. try {
  90. input.close()
  91. } catch (e: IOException) {
  92. }
  93. if (out != null)
  94. try {
  95. out.close()
  96. } catch (e: IOException) {
  97. }
  98. response.close()
  99. }
  100. }
  101. })
  102. }
  103. fun cancel() {
  104. synchronized(this, {
  105. if (!isCancel) {
  106. isCancel = true
  107. call.cancel()
  108. }
  109. })
  110. }
  111. }

看起来好像比较长,那么我们来看看使用效果

  1. class MainActivity : AppCompatActivity() {
  2. override fun onCreate(savedInstanceState: Bundle?) {
  3. super.onCreate(savedInstanceState)
  4. setContentView(R.layout.activity_main)
  5. val image = findViewById(R.id.imageView) as ImageView
  6. val url = "http://192.168.1.112:8080/smart/okhttp/get/cover"
  7. val utils = DownloadUtils(url,
  8. { current, max, speed ->
  9. Log.e("progress", "当前下载进度: ${current * 100 / max}% 下载速度${speed / 1024}KB/s")
  10. },
  11. Exception::printStackTrace,
  12. {
  13. Log.e("completed", "下载完成")
  14. val bitmap = BitmapFactory.decodeByteArray(it, 0, it.size)
  15. image.setImageBitmap(bitmap)
  16. })
  17. utils.start()
  18. }
  19. }

在控制台看到输出了如下内容

E/progress: 当前下载进度: 10%  下载速度57KB/s
E/progress: 当前下载进度: 15%  下载速度24KB/s
E/progress: 当前下载进度: 15%  下载速度2KB/s
E/progress: 当前下载进度: 15%  下载速度1KB/s
E/progress: 当前下载进度: 18%  下载速度12KB/s
E/progress: 当前下载进度: 19%  下载速度8KB/s
E/progress: 当前下载进度: 24%  下载速度25KB/s
E/progress: 当前下载进度: 27%  下载速度18KB/s
E/progress: 当前下载进度: 34%  下载速度36KB/s
E/progress: 当前下载进度: 48%  下载速度72KB/s
E/progress: 当前下载进度: 76%  下载速度152KB/s
E/completed: 下载完成
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注