Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin & Retrofit: Simple POST without Response

I'm trying to do a POST Request with Kotlin and Retrofit where I'm only interested in the statuscode of the request. Tutorials I have seen solve it all a bit different and most of the time they do not compile any more or are very complicated.

Can someone help improving this code:?

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)
            }
        } 
    }

I'm not sure how to call it and how to get the statuscode.

like image 976
netshark1000 Avatar asked Feb 21 '18 20:02

netshark1000


People also ask

What is Kotlin is used for?

What can I use Kotlin for? Kotlin can be used for any kind of development, be it server-side, client-side web and Android. With Kotlin/Native currently in the works, support for other platforms such as embedded systems, macOS and iOS is coming.

Is Kotlin better than Java?

Kotlin Application Deployment is faster to compile, lightweight, and prevents applications from increasing size. Any chunk of code written in Kotlin is much smaller compared to Java, as it is less verbose and less code means fewer bugs. Kotlin compiles the code to a bytecode which can be executed in the JVM.

Is Kotlin Just Java?

Even though Kotlin is a full-fledged functional programming language, it preserves most of the object-oriented nature of Java as an alternative programming style, which is very handy when converting existing Java code.

Is Kotlin vs Python?

Python is the best dynamic language but it is worth learning a statistically typed language. Large projects demand the rigour of a statically typed language, Kotlin can provide that rigour with no drawbacks such as verbose syntax. Learning Kotlin will teach you more about coding.


1 Answers

Try this example

Under 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:

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)

}

Retrofit Client:

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("[email protected]", "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) {

                }
            })
like image 75
Arun Avatar answered Oct 26 '22 21:10

Arun