Eswar
Eswar

Reputation: 1212

Unable to POST my data using retrofit android using kotlin

I am new to android studio and kotlin. I have trying to post my data(object) onto the server but I'm getting a 404 response code.

My retrofit:

object RetrofitClient {
private var OurInstance : Retrofit?=null
val client = OkHttpClient.Builder()
val instance:Retrofit
get() {
    if (OurInstance==null)
    {
        OurInstance =Retrofit.Builder()
                .baseUrl("http://coreapi.imagin8ors.org:8080/")
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build()
    }
    return OurInstance!!
  }
}

My interface:

interface IMyAPI {
@GET("v1/child/{dynamic}/learningpods_new")
fun getDynamic(@Path("dynamic")dynamic:String):Observable<ArrayList<Data>>

@POST("v1/authenticate/create")
fun createParent(@Body parentDetails: ParentDetails):Call<ParentDetails>
}

Code snippet in my activity:

fun sendNetworkRequest(parentDetails: ParentDetails){
    val retrofit=Retrofit.Builder().baseUrl("http://coreapi.imagin8ors.org:8080/")
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    val client=retrofit.create(IMyAPI::class.java)
    val call = client.createParent(parentDetails)
    call.enqueue(object :Callback<ParentDetails>{
        override fun onFailure(call: Call<ParentDetails>?, t: Throwable?) {
            Toast.makeText(this@ParentmainActivity,"something went wrong",Toast.LENGTH_LONG).show()
        }

        override fun onResponse(call: Call<ParentDetails>?, response: Response<ParentDetails>?) {
            Toast.makeText(this@ParentmainActivity,"successful :"+response?.code(),Toast.LENGTH_LONG).show()
        }

    })
}

Function call: sendNetworkRequest(new_parent)

Now, the response code returned is 404. This issue has been raised previously but those solutions didn't work for me. That's why I have posted as another question.

The links I have referred to: link1, link2, link3 and many more..

Initially I was using the retrofitclient but then it didn't work so I tried with the sendNetworkResquest() function. However, this too doesn't work.

Upvotes: 0

Views: 1996

Answers (1)

nsndvd
nsndvd

Reputation: 830

I think what you need is a PUT request. When I try your API with POST I actually get a 405 - Method Not Allowed. But PUT works.. except that I am sending no data, so I get a 400. But definitely not a 404

curl -X POST http://.../create -> Method not allowed
curl -X PUT http://.../create -> Bad Request

Also double check that your body actually contains valid data in the required format, as specified by your backend endpoint, otherwise you'll get further errors

Upvotes: 1

Related Questions