Mark
Mark

Reputation: 79

Retrofit. POST with request body without response body

I try to POST these login and password

{
    "userLogin": "Mark",
    "userPassword": "Pencil"
}

According to POSTMAN, where I put above JSON as a raw code, I got an empty response body and response code: 200 (Logging is succesful). But I can't achieve it in Android Studio. Here is an API interface

interface LoginService {
    @POST("login")
    fun userLogin(
        @Query("userLogin") userLogin: String,
        @Query("userPassword") userPassword: String
    ):Call<Void>
}

And here is Retrofit:

fun checkLoginData() {
        val retrofit = Retrofit.Builder()
            .baseUrl("myurl...")
            .addConverterFactory(GsonConverterFactory.create())
            .build()
        val service = retrofit.create(LoginService::class.java)
        val call = service.userLogin("Mark", "Pencil")

        call.enqueue(object : Callback<Void>{
            override fun onResponse(call: Call<Void>, response: Response<Void>) {
            if(response.code() == 200){
                Toast.makeText(applicationContext,"Logged in", Toast.LENGTH_SHORT).show()

            }
        }

            override fun onFailure(call: Call<Void>, t: Throwable) {
            Toast.makeText(applicationContext,"Error", Toast.LENGTH_SHORT).show()
        }

    })
}

I suppose that my LoginService is created incorrectly because there is always onFailure response. How should I do it rightly?

Upvotes: 1

Views: 4128

Answers (2)

r2rek
r2rek

Reputation: 2233

Using POST you'll probably not use @Query, but rather a @Body. E.g.

data class LoginRequest(
val userLogin: String,
val userPassword: String
)

and in your interface :

 @POST("login")
    fun userLogin(@Body request: LoginRequest):Call<Void>

EDIT: Since it's an issue with ClearText: You need to add android:usesCleartextTraffic="true" to your AndroidManifest. Refer to Android 8: Cleartext HTTP traffic not permitted Option 2 for more info.

Upvotes: 1

Aditya Jaitly
Aditya Jaitly

Reputation: 292

Use @Body instead of @Query

  @Headers("Content-Type: application/json")
  @POST("login")
  fun userLogin(@Body rawParams: String):Call<Void>

Then you can create parameter like this

  val params= JSONObject()
  params.put("userLogin","Mark")
  params.put("userPassword","Pencil")

Last change in

 val call = service.userLogin(params.toString())

Error Solution for cleartext is Create file

   res/xml/network_security_config.xml

   <?xml version="1.0" encoding="utf-8"?>
    <network-security-config>
    <base-config cleartextTrafficPermitted="true">
    <trust-anchors>
        <certificates src="system" />
    </trust-anchors>
    </base-config>
    </network-security-config>

And Then Add in Manifest

 <application 
      android:networkSecurityConfig="@xml/network_security_config"
    ...>

Upvotes: 1

Related Questions