Advertisement
Guest User

Untitled

a guest
Mar 25th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.28 KB | None | 0 0
  1. /////////////////////////////
  2. object SafeHttpClient {
  3. private const val TAG = "STaxi.SafeHttpClient"
  4.  
  5. val safeOkHttpClient: OkHttpClient
  6. get() {
  7. Log.d(TAG, "return builder.build()")
  8.  
  9. return OkHttpClient.Builder()
  10. .addInterceptor(NetInterceptor())
  11. .build()
  12. }
  13. }
  14. //////////////////////////////
  15. object RetrofitClient {
  16. private const val BASE_URL = "https://www.your.site/api/"
  17. private const val TAG = "RetrofitClient"
  18.  
  19. val instance: Retrofit by lazy {
  20. Log.d(TAG, "instance = new Retrofit.Builder()....build()")
  21. Retrofit.Builder()
  22. .baseUrl(BASE_URL)
  23. .client(SafeHttpClient.safeOkHttpClient)
  24. .addConverterFactory(GsonConverterFactory.create())
  25. .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
  26. .build()
  27. }
  28. }
  29. //////////////////////////////
  30. class NetInterceptor : Interceptor {
  31. private val TAG = "NetInterceptor"
  32.  
  33. @Throws(IOException::class)
  34. override fun intercept(chain: Interceptor.Chain): Response {
  35. val request = chain.request()
  36.  
  37. when {
  38. request.method().equals("post", ignoreCase = true) -> {
  39. if (
  40. request.url().encodedPath().equals("/api/login", ignoreCase = true) ||
  41. request.url().encodedPath().equals("/api/registration/register", ignoreCase = true) ||
  42. request.url().encodedPath().equals("/api/registration/resendCode", ignoreCase = true) ||
  43. request.url().encodedPath().equals("/api/registration/confirm", ignoreCase = true) ||
  44. request.url().encodedPath().equals("/api/payment/result", ignoreCase = true)
  45. ) {
  46. Log.d(TAG, "post ${request.url().encodedPath()}")
  47. return chain.proceed(request.newBuilder()
  48. .build())
  49. }
  50. }
  51. request.method().equals("get", ignoreCase = true) -> {
  52. if (
  53. request.url().encodedPath().contains("/api/news", ignoreCase = true) ||
  54. request.url().encodedPath().equals("/api/public/subscriptionTypes", ignoreCase = true)
  55. ) {
  56. Log.d(TAG, "get ${request.url().encodedPath()}")
  57. return chain.proceed(request.newBuilder()
  58. .build())
  59. }
  60. }
  61. }
  62.  
  63. val newRequest = request.newBuilder()
  64. .addHeader("Authorization", "Bearer ${AppEx.instance!!.shpToken}") // здесь токен подставляется
  65. .build()
  66. Log.d(TAG, "Auth ${request.url().encodedPath()}")
  67. Log.d(TAG, "Auth ${AppEx.instance!!.shpToken}")
  68. return chain.proceed(newRequest)
  69. }
  70. }
  71. //////////////////////////////////
  72. interface AccountApi {
  73.  
  74. @FormUrlEncoded
  75. @POST("login")
  76. fun login(
  77. @Field("username") username: String,
  78. @Field("password") password: String
  79. ): Observable<Response<Unit>>
  80.  
  81. @FormUrlEncoded
  82. @POST("account/changePassword")
  83. fun changePassword(
  84. @Field("oldPassword") oldPassword: String,
  85. @Field("newPassword") newPassword: String
  86. ): Observable<Response<Unit>>
  87.  
  88. @FormUrlEncoded
  89. @POST("account/usedSystems")
  90. fun updateUsedSystems(
  91. @Body jsonString: String
  92. ): Observable<Response<Unit>>
  93.  
  94. @GET("auth/user")
  95. fun getAuthUserDetails() : Observable<Response<AuthUserDetailsDto>>
  96.  
  97. @GET("account/person")
  98. fun currentPerson(): Observable<Response<PersonDto>>
  99.  
  100. @GET("auth/ping")
  101. fun ping(): Observable<Response<Unit>>
  102.  
  103. }
  104. /////////////////////////////////
  105. // где-то в коде
  106. // проверка последнего использованного токена
  107. private fun ping() {
  108. compositeDisposable.add(accApi.ping()
  109. .subscribeOn(Schedulers.io())
  110. .observeOn(AndroidSchedulers.mainThread())
  111. .subscribe(this::handlePingResponse, this::handlePingError)
  112. }
  113.  
  114. private fun handlePingResponse(result: Response<Unit>) {
  115. when {
  116. result.isSuccessful -> {
  117. Log.d(TAG, "Authorization completed by log+pass+token")
  118. compositeDisposable.add(accApi.currentPerson()
  119. .subscribeOn(Schedulers.io())
  120. .observeOn(AndroidSchedulers.mainThread())
  121. .subscribe(this::handleCurrentPersonResponse, this::handleCurrentPersonError)
  122. )
  123. compositeDisposable.add(accApi.getAuthUserDetails()
  124. .subscribeOn(Schedulers.io())
  125. .observeOn(AndroidSchedulers.mainThread())
  126. .subscribe(this::handleAuthUserDetailsResponse, this::handleAuthUserDetailsError))
  127. }
  128. else -> login(AppEx.instance!!.shpLogin, AppEx.instance!!.shpPass)
  129. }
  130. }
  131.  
  132. private fun handlePingError(error: Throwable) {
  133. Log.d(TAG, "handlePingError: ${error.message}")
  134. login(AppEx.instance!!.shpLogin, AppEx.instance!!.shpPass)
  135. }
  136. // и так далее
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement