Gregor A
Gregor A

Reputation: 237

Retrofit doesn't send POST request

I can't seem to get the POST request working with Retrofit. My code:

ApiService.kt contains a function

@Headers("Content-Type: application/json")
@POST("resume")
suspend fun resumeAsync(@Body request: JSONObject): Response<String>

Then in my ListViewModel.kt I have a function

fun resume(id: String) {
    coroutineScope.launch {
        try {
            val paramObject = JSONObject()
            paramObject.put("id", id)

            val response = Api.retrofitService.resumeAsync(paramObject)
            if (response.isSuccessful) {
                _status.value = "Success: Resumed!"
            }
        } catch (e: Exception) {
            _status.value = "Failure: " + e.message
        }
    }
}

Why is this not working? I don't get any error or response back. If I put Log.i in the Api or the view model it says it's triggered

By debugging I found out this error:

2020-09-15 11:40:10.904 20622-20622/com.example.app I/NETWORK: Unable to create @Body converter for class org.json.JSONObject (parameter #1) for method ApiService.resumeAsync

I am using Moshi as well

private val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()

private val retrofit = Retrofit.Builder()
    .addConverterFactory(MoshiConverterFactory.create(moshi))
    .baseUrl(BASE_URL)
    .build()

Upvotes: 0

Views: 1849

Answers (4)

Vlad
Vlad

Reputation: 8572

If you need to receive raw json then use Call<*>

@Headers("Content-Type: application/json")
@POST("resume")
fun resumeAsync(@Body request: JSONObject): retrofit2.Call<String>

Inside coroutine (without suspend keyword above)

// or .awaitResponse() to get Response<*> object
val response = Api.retrofitService.resumeAsync(paramObject).await()

Upvotes: 2

Paul Nitu
Paul Nitu

Reputation: 126

You can try adding a logging interceptor to your okHttp client and check what you're sending and receiving in the request.

val logging = HttpLoggingInterceptor()
logging.setLevel(HttpLoggingInterceptor.Level.BODY)

Is the url/endpoint correct?

Are you missing a "/" at the end of the url?

Have you declared internet permission in the manifest?

etc.

Solution:

Wrapping request body:

@Body body: RequestBody 

val body = RequestBody.create(MediaType.parse("application/json"), obj.toString())

Upvotes: 2

Gregor A
Gregor A

Reputation: 237

So I solved my problem by doing what @Paul Nitu recommended

val body = RequestBody.create(MediaType.parse("application/json"), obj.toString())

Upvotes: 0

MuseYkh
MuseYkh

Reputation: 51

Can you debug on this line

if (response.isSuccessful) {

try to check the variable response;

Or you shoud check whether the server is work, check it with other tools like Postman

Upvotes: 1

Related Questions