实现一个极简的 DSL

OkHttp是一个成熟且强大的网络库,在Android源码中已经使用OkHttp替代原先的HttpURLConnection。很多著名的框架例如Picasso、Retrofit也使用OkHttp作为底层框架。在这里我对OkHttp做一下简单的封装,其实封装得有点粗暴只是为了演示如何实现dsl。

  1. import io.reactivex.BackpressureStrategy
  2. import io.reactivex.Flowable
  3. import io.reactivex.schedulers.Schedulers
  4. import okhttp3.OkHttpClient
  5. import okhttp3.Request
  6. import okhttp3.RequestBody
  7. import okhttp3.Response
  8. import java.util.concurrent.TimeUnit
  9. class RequestWrapper {
  10. var url:String? = null
  11. var method:String? = null
  12. var body: RequestBody? = null
  13. var timeout:Long = 10
  14. internal var _success: (String) -> Unit = { }
  15. internal var _fail: (Throwable) -> Unit = {}
  16. fun onSuccess(onSuccess: (String) -> Unit) {
  17. _success = onSuccess
  18. }
  19. fun onFail(onError: (Throwable) -> Unit) {
  20. _fail = onError
  21. }
  22. }
  23. fun http(init: RequestWrapper.() -> Unit) {
  24. val wrap = RequestWrapper()
  25. wrap.init()
  26. executeForResult(wrap)
  27. }
  28. private fun executeForResult(wrap:RequestWrapper) {
  29. Flowable.create<Response>({
  30. e -> e.onNext(onExecute(wrap))
  31. }, BackpressureStrategy.BUFFER)
  32. .subscribeOn(Schedulers.io())
  33. .subscribe(
  34. { resp ->
  35. wrap._success(resp.body()!!.string())
  36. },
  37. { e -> wrap._fail(e) })
  38. }
  39. private fun onExecute(wrap:RequestWrapper): Response? {
  40. var req:Request? = null
  41. when(wrap.method) {
  42. "get","Get","GET" -> req =Request.Builder().url(wrap.url).build()
  43. "post","Post","POST" -> req = Request.Builder().url(wrap.url).post(wrap.body).build()
  44. "put","Put","PUT" -> req = Request.Builder().url(wrap.url).put(wrap.body).build()
  45. "delete","Delete","DELETE" -> req = Request.Builder().url(wrap.url).delete(wrap.body).build()
  46. }
  47. val http = OkHttpClient.Builder().connectTimeout(wrap.timeout, TimeUnit.SECONDS).build()
  48. val resp = http.newCall(req).execute()
  49. return resp
  50. }

封装完OkHttp之后,看看如何来编写get请求

  1. http {
  2. url = "http://www.163.com/"
  3. method = "get"
  4. onSuccess {
  5. string -> L.i(string)
  6. }
  7. onFail {
  8. e -> L.i(e.message)
  9. }
  10. }

是不是很像以前用jquery来写ajax?

post请求也是类似的,只不过多了body

  1. var json = JSONObject()
  2. json.put("xxx","yyyy")
  3. ....
  4. val postBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),json.toString())
  5. http {
  6. url = "https://......"
  7. method = "post"
  8. body = postBody
  9. onSuccess {
  10. string -> L.json(string)
  11. }
  12. onFail {
  13. e -> L.i(e.message)
  14. }
  15. }