Kotlin&改造:没有响应的简单POST

时间:2018-02-21 20:04:38

标签: rest kotlin retrofit

我正在尝试使用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)
            }
        } 
    }

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

2 个答案:

答案 0 :(得分:7)

试试这个例子

在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

    }
}

MainActivity

  //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) {

                }
            })

答案 1 :(得分:0)

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

 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()方法中获得成功响应/结果。