【问题标题】:Kotlin & Retrofit: Simple POST without ResponseKotlin & Retrofit:没有响应的简单 POST
【发布时间】:2018-08-01 13:00:39
【问题描述】:

我正在尝试使用 Kotlin 和 Retrofit 进行 POST 请求,我只对请求的状态码感兴趣。我见过的教程解决了这一切有点不同,大多数时候它们不再编译或非常复杂。

有人可以帮助改进这段代码吗?

interface ClientService {

        @POST("user/password-reset")
        fun passwortReset(@Query("email") email: String): Observable<Result>

        companion object {
            fun create(): ClientService {

                val retrofit = Retrofit.Builder()
                        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                        .addConverterFactory(GsonConverterFactory.create())
                        .baseUrl("https://test-backend.myurl.com/api/")
                        .build()

                return retrofit.create(ClientService::class.java)
            }
        } 
    }

我不知道如何调用它以及如何获取状态码。

【问题讨论】:

    标签: rest kotlin retrofit


    【解决方案1】:

    试试这个例子

    在 build.gradle 下:

       // retrofit
    
        compile "com.squareup.retrofit2:retrofit:2.3.0"
    
        compile "com.squareup.retrofit2:adapter-rxjava2:2.3.0"
        compile "com.squareup.retrofit2:converter-gson:2.3.0"
    
        // rxandroid
    
        compile "io.reactivex.rxjava2:rxandroid:2.0.1"
        compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
        compile 'com.squareup.okhttp3:okhttp:3.4.1'
    

    界面:

    interface APIService {
    
        @POST("register")
        @FormUrlEncoded
        fun registrationPost(@Field("email") email: String,
                             @Field("password") password: String): Call<Registration>}
    
    
    //**App Utils**
    
    object ApiUtils {
    
        val BASE_URL = "your_url"
    
        val apiService: APIService
            get() = RetrofitClient.getClient(BASE_URL)!!.create(APIService::class.java)
    
    }
    

    改造客户端:

    object RetrofitClient {
    
        var retrofit: Retrofit? = null
    
        fun getClient(baseUrl: String): Retrofit? {
            if (retrofit == null) {
                //TODO While release in Google Play Change the Level to NONE
                val interceptor = HttpLoggingInterceptor()
                interceptor.level = HttpLoggingInterceptor.Level.BODY
                val client = OkHttpClient.Builder()
                        .addInterceptor(interceptor)
                        .connectTimeout(100, TimeUnit.SECONDS)
                        .readTimeout(100, TimeUnit.SECONDS)
                        .build()
    
                retrofit = Retrofit.Builder()
                        .client(client)
                        .baseUrl(baseUrl)
                        .addConverterFactory(GsonConverterFactory.create())
                        .build()
            }
    
            return retrofit
    
        }
    }
    

    主活动

      //Variable declaration
      var mAPIService: APIService? = null
    
      //After oncreate
    
       mAPIService = ApiUtils.apiService
    
      //Some Button click
    
           mAPIService!!.registrationPost("SampleTest2@gamil.com", "123456").enqueue(object : Callback<Registration> {
    
                    override fun onResponse(call: Call<Registration>, response: Response<Registration>) {
    
                        Log.i("", "post submitted to API." + response.body()!!)
    
                        if (response.isSuccessful()) {
    
                            Log.i("", "post registration to API" + response.body()!!.toString())
                            Log.i("", "post status to API" + response.body()!!.status)
                            Log.i("", "post msg to API" + response.body()!!.messages)
    
                        }
                    }
    
                    override fun onFailure(call: Call<Registration>, t: Throwable) {
    
                    }
                })
    

    【讨论】:

    • MainActivity 中的“创建后”注释是什么意思?你的意思是在“onResume”函数中还是在“OnCreate”或其他东西的末尾?还有你必须为“Callback”导入哪些库,Android Studio 推荐了很多库。
    【解决方案2】:

    在你必须调用的任何函数中:

     fun resetPassword(email:String) {
    
        val clientService = ClientService.create(APIConstants
                .BASE_URL_WORKSPACE)
        addSubscription(apiService.login(APIConstants.API_ACTION_LOGIN, userName, password,
                deviceid), object : APICallback<UserLoginResponse>() {
            override fun onSuccess(model: UserLoginResponse) {
                if (TextUtils.isEmpty(model.errorMessage)) {
                    mvpView.getDataSuccess(model, apiRequestCode)
                } else {
                    mvpView.getDataFail(model.errorMessage, apiRequestCode)
                }
            }
    
            override fun onFailure(msg: String?) {
                LogUtil.e("Login Failure()- " + msg!!)
            }
    
            override fun onFinish() {}
        })
     }
    

    您将在 onSuccess() 方法中获得成功响应/结果。

    【讨论】:

      猜你喜欢
      • 2016-12-26
      • 2018-08-23
      • 1970-01-01
      • 2020-02-24
      • 2020-10-26
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 2019-10-09
      相关资源
      最近更新 更多