Retrofit response with internal error with code 500 - api

trying to use post/put call method in my Kotlin frontend to get response from Django backend. Method Get works but if I use ResponseBody nothing happens and log gives error with code 500.
Can someone help me?
This is my Api interface, where PUT and POST method doesnt work
public interface Api {
#GET("api/users")
fun getUsers(): Call<UserResults>
#PUT("/api/users/{Id}")
suspend fun updateUser(#Body requestBody: RequestBody, #Path("Id") userId: String): Response<ResponseBody>
#POST("/api/users")
suspend fun createUser(#Body requestBody: RequestBody): Response<ResponseBody>
}
This is function for example for PUT method
private fun updateSettings(preferredBranch: String) {
// Create Retrofit
val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.build()
// Create Service
val service = retrofit.create(Api::class.java)
// Create JSON using JSONObject
val jsonObject = JSONObject()
jsonObject.put("preferred_branch", preferredBranch)
//jsonObject.put("job", "iOS Developer")
// Convert JSONObject to String
val jsonObjectString = jsonObject.toString()
// Create RequestBody ( We're not using any converter, like GsonConverter, MoshiConverter e.t.c, that's why we use RequestBody )
val requestBody = jsonObjectString.toRequestBody("application/json".toMediaTypeOrNull())
CoroutineScope(Dispatchers.IO).launch {
// Do the PUT request and get response
val response = service.updateUser(requestBody, logId.toString())
withContext(Dispatchers.Main) {
if (response.isSuccessful) {
// Convert raw JSON to pretty JSON using GSON library
val gson = GsonBuilder().setPrettyPrinting().create()
val prettyJson = gson.toJson(
JsonParser.parseString(
response.body()
?.string() // About this thread blocking annotation : https://github.com/square/retrofit/issues/3255
)
)
Log.d("Pretty Printed JSON :", "test")
} else {
Log.e("RETROFIT_ERROR", response.code().toString())
}
}
}
}

Related

Retrofit response body returning null

I've been stuck with this problem for some time now, and I can't seem to find the problem especially when all I did was following a guide online.
I'm trying to make a POST request, and receive a response in exchange:
Request body:
{
"Email":"test#gmail.com",
"firebaseUid":"Test_UID",
"IsBanned":1
}
Response body:
`
{
"Email": "test#gmail.com",
"UserId": 7
}
So basically whenever I submit a request to /users/ to create an account, I get both the email and UserId returned.
data class UserLogin(
#SerializedName("Email") val Email: String,
#SerializedName("UserId") val UserId: Int?,
#SerializedName("IsBanned") val IsBanned: Boolean?,
#SerializedName("firebaseUid") val firebaseUid: String?
)
object ServiceBuilder {
private val client = OkHttpClient.Builder().build()
private val retrofit = Retrofit.Builder()
.baseUrl("http://10.0.2.2/8000/")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build()
fun<T> buildService(service: Class<T>): T{
return retrofit.create(service)
}
}
class RestApiService {
fun addUser(userData: UserLogin, onResult: (UserLogin?) -> Unit){
val retrofit = ServiceBuilder.buildService(RestApi::class.java)
retrofit.addUser(userData).enqueue(
object : Callback<UserLogin> {
override fun onFailure(call: Call<UserLogin>, t: Throwable) {
Log.d("Failed retrofit",t.message.toString())
onResult(null)
}
override fun onResponse( call: Call<UserLogin>, response: Response<UserLogin>) {
val addedUser = response.body()
onResult(addedUser)
}
}
)
}
}
onFailure doesn't seem to be printing anything on the console. I'm calling the API from a button like this and both Email and UserId keep returning null for some reason:
`
val apiService = RestApiService()
val userInfo = UserLogin(UserId = null,firebaseUid = "TestTestTest", IsBanned = false, Email = "test#gmail.com");
apiService.addUser(userInfo){
Log.d("Retrofit user added", it?.Email.toString())
}
`
I tried to:
Set default values for the data class members.
Tried to check if response is successfull, and then print the errorBody if not. That didn't help either. I'm getting unreadable errors like $1#9afe35d instead.
Everything seem to be working fine when I do requests manually with POSTMAN.
It turned out there was nothing with the code. I just typed the port the wrong way and used a / instead of :
private val retrofit = Retrofit.Builder()
.baseUrl("http://10.0.2.2:8000/") // this
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build()

How to create an HttpResponse object with dummy values in ktor Kotlin?

I am using ktor for developing a microservice in Kotlin. For testing a method, I need to create a dummy HttpResponse (io.ktor.client.statement.HttpResponse to be specific) object with status = 200 and body = some json data.
Any idea how I can create it?
You can use mockk or a similar kind of library to mock an HttpResponse. Unfortunately, this is complicated because HttpRequest, HttpResponse, and HttpClient objects are tightly coupled with the HttpClientCall. Here is an example of how you can do that:
val call = mockk<HttpClientCall> {
every { client } returns mockk {}
coEvery { receive(io.ktor.util.reflect.typeInfo<String>()) } returns "body"
every { coroutineContext } returns EmptyCoroutineContext
every { attributes } returns Attributes()
every { request } returns object : HttpRequest {
override val call: HttpClientCall = this#mockk
override val attributes: Attributes = Attributes()
override val content: OutgoingContent = object : OutgoingContent.NoContent() {}
override val headers: Headers = Headers.Empty
override val method: HttpMethod = HttpMethod.Get
override val url: Url = Url("/")
}
every { response } returns object : HttpResponse() {
override val call: HttpClientCall = this#mockk
override val content: ByteReadChannel = ByteReadChannel("body")
override val coroutineContext: CoroutineContext = EmptyCoroutineContext
override val headers: Headers = Headers.Empty
override val requestTime: GMTDate = GMTDate.START
override val responseTime: GMTDate = GMTDate.START
override val status: HttpStatusCode = HttpStatusCode.OK
override val version: HttpProtocolVersion = HttpProtocolVersion.HTTP_1_1
}
}
val response = call.response
I did this with following. I only needed to pass a status code and description, so I didn't bother about other fields.
class CustomHttpResponse(
private val statusCode: Int,
private val description: String
) :
HttpResponse() {
#InternalAPI
override val content: ByteReadChannel
get() = ByteReadChannel("")
override val call: HttpClientCall
get() = HttpClientCall(HttpClient())
override val coroutineContext: CoroutineContext
get() = EmptyCoroutineContext
override val headers: Headers
get() = Headers.Empty
override val requestTime: GMTDate
get() = GMTDate()
override val responseTime: GMTDate
get() = GMTDate()
override val status: HttpStatusCode
get() = HttpStatusCode(statusCode, description)
override val version: HttpProtocolVersion
get() = HttpProtocolVersion(name = "HTTP", major = 1, minor = 1)}
With Ktor 2, it's best to use externalServices block instead of attempting to mock HttpResponse. That way you don't need to attempt and mock the internals of Ktor, and it's not complicated at all.
externalServices {
hosts("https://your-fake-host") {
routing {
get("/api/v1/something/{id}/") {
call.respondText(
"{}",
contentType = ContentType.Application.Json,
status = HttpStatusCode.OK
)
}
}
}
}
This need to be wrapped with testApplication

How to return an object from an api-call-function in Kotlin? [duplicate]

How can I return a value after a callback in kotlin, I tried using Thread.sleep but it doesn't work
fun searchColorFromAPI(): Colors {
val service: RetrofitService = ServiceGenerator.createService(RetrofitService::class.java)
val result: MutableList<String> = arrayListOf()
val call: Call<Colors?>? = service.unityConverter(result)
call?.enqueue(object : Callback<Colors?> {
override fun onResponse(call: Call<Colors?>?, response: Response<Colors?>) {
//switchProgressVisibility()
if (response.isSuccessful) {
val serviceResponse: Colors? = response.body()
if (serviceResponse != null) {
mColors = serviceResponse
}
else {
//buildToast(getString(R.string.null_response))
}
}
else {
//buildToast(getString(R.string.response_unsuccessful))
val errorBody: ResponseBody = response.errorBody()
Log.e(TAG, errorBody.toString())
}
}
override fun onFailure(call: Call<Colors?>?, t: Throwable?) {
/* buildToast(getString(R.string.error_calling_service))
Log.e(TAG, t?.message)*/
}
})
return mColors
}
Always, the mColors is returned before the onFailure or onResponse because they're asynchronous. Before this code was in MainActivity but I was advised to take off, but now when I try get mColors I get the empty value before and after the onResponse is executed, please I'm still learning Kotlin and Android.
Your problem stems from the fact that Retrofit call is asynchronous, so as soon as you call searchColorFromAPI it returns you mColors but the API call may not have been made yet, so you get the mColors value before API call.
To solve this issue, you can do
Use callback, this will require little modification in your current setup, but the 2nd option is preferable over this. Using callback your function should look like this.
/* Now instead of returning a value, your function takes a function (named callback)
as parameter. when your api call finishes, you can call the callback function and
pass the api response.
*/
fun searchColorFromAPI(callback: (Colors?) -> Unit) {
val service: RetrofitService = ServiceGenerator.createService(RetrofitService::class.java)
val result: MutableList<String> = arrayListOf()
val call: Call<Colors?>? = service.unityConverter(result)
call?.enqueue(object : Callback<Colors?> {
override fun onResponse(call: Call<Colors?>?, response: Response<Colors?>) {
//switchProgressVisibility()
if (response.isSuccessful) {
val serviceResponse: Colors? = response.body()
/** pass API response to callback */
callback(serviceResponse)
}
else {
val errorBody: ResponseBody = response.errorBody()
Log.e(TAG, errorBody.toString())
callback(null)
}
}
override fun onFailure(call: Call<Colors?>?, t: Throwable?) {
callback(null)
}
})
}
And in your activity declare a function as follows.
// This function will be called when your api call finishes
// and it will give you the api response
fun apiCallback(colors: Colors?){
if(colors == null){
// API Call failed
}
else{
// use colors as returned by API
}
}
And now call to searchColorFromApi should look like this
searchColorFromApi(apiCallback)
Use Live Data, declare following field in your viewmodel, if you are not using viewmodel then declare it in the class which has searchColorFromApi function.
var colors: MutableLiveData<Colors> = MutableLiveData()
and modify your searchColorFromAPI function as follows
fun searchColorFromAPI() {
val service: RetrofitService = ServiceGenerator.createService(RetrofitService::class.java)
val result: MutableList<String> = arrayListOf()
val call: Call<Colors?>? = service.unityConverter(result)
call?.enqueue(object : Callback<Colors?> {
override fun onResponse(call: Call<Colors?>?, response: Response<Colors?>) {
//switchProgressVisibility()
if (response.isSuccessful) {
val serviceResponse: Colors? = response.body()
if (serviceResponse != null) {
colors.postValue(response.body)
}
}
else {
colors.postValue(null)
val errorBody: ResponseBody = response.errorBody()
Log.e(TAG, errorBody.toString())
}
}
override fun onFailure(call: Call<Colors?>?, t: Throwable?) {
colors.postValue(null)
}
})
}
and in your activity do following
fun setupObservers(){
yourApiCallingClass.colors.observe(this, Observer {
// this code is called when ever value of color field changes
})
}
You can use live data ,that gets updated once the callback receives ,the same live data is observed by the caller fragment/activity
You can use coroutines to return a value from function which has asyn calls in it.
You can use interface callbacks to activity/ fragment to trigger the updates received from retrofit calls.

What is the parameter for request and response body okhttp in kotlin

I start to code the app in kotlin with okhttp3. I get response body but how I can get the info that I need? For example, I use Google example. I just want to get the "name:". How I can tell my request that I what get only "name:"? Can you help with some code example or some source with instruction and description about OkHTTP? I read official documentation but didn't find something or just didn't understand.
fun run(url: String){
val request = Request.Builder().url(url).build()
//client.authenticator()
val client = OkHttpClient()
.newBuilder()
.addInterceptor { chain ->
val originalRequest = chain.request()
val builder = originalRequest
.newBuilder()
val name = request.header("name")
//.header("Authorization",
// Credentials.basic("login", "password"))
val newRequest = builder.build()
chain.proceed(newRequest)
}.build()
client.newCall(request).enqueue(object : Callback{
override fun onFailure(call: Call, e: IOException) {
toast("fail")
e.printStackTrace()
}
override fun onResponse(call: Call, response: Response) {
textView3.setText(response.body()?.string())
}
})
I tried to use .header("name") but it was red and I think I make some mistake.
Thank for every suggestions
Here is a way to do it with Jackson ObjectMapper
as per your example, let's say you receive the following content in the response:
{
"login": "defunkt",
"id": 2,
"name": "Chris Wanstrath",
"company": null,
"blog": "http://chriswanstrath.com/"
}
but you are only interested to in the name field, therefore you define a User class:
public class User { private String name; }
and then using the ObjectMapper configured to ignore the missing properties:
// content = response.body().string();
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
try {
User user = mapper.readValue(content, User.class);
System.out.println(user.getName()); // Chris Wanstrath
} catch (JsonProcessingException e) {
e.printStackTrace();
}

Retrofit 2 Get Github Users API always returning null

I tried to get json from the https://github.com/users.
I want to show username : yehezkiell like https://github.com/yehezkiell.
The retrofit showing success result, but its always return null. I'm new in this retrofit, please help
this my code
val postService = DataRepository.create()
postService.getUser("yehezkiell").enqueue(object : Callback<Users>{
override fun onFailure(call: Call<Users>?, t: Throwable?) {
Log.e("retrofitnya","gagal ${t}")
}
override fun onResponse(call: Call<Users>?, response: Response<Users>?) {
Log.e("retrofitnya","berhasil")
val data = response?.body()
Log.e("retrofitnya","berhasil ${data?.name}")
}
})
Retrofit Instance
interface RetrofitInstance {
#GET("users/{username}")
fun getUser(#Path("username") username:String ): Call<Users>
}
Data repo
object DataRepository {
fun create(): RetrofitInstance {
val retrofit = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("https://github.com")
.build()
return retrofit.create(RetrofitInstance::class.java)
}
}
Users.kt
open class Users {
#SerializedName("name")
#Expose
open var name: String? = null
#SerializedName("username")
#Expose
open var username: String? = null
#SerializedName("email")
#Expose
open var email: String? = null
}
For debugging process, instead of de-serialization to Users object immediately after response, should we do somethings like these? :
De-serialize it to plain string first.
interface RetrofitInstance {
#GET("users/{username}")
fun getUser(#Path("username") username: String): Call<String>
}
Just log that string to show what we really get.
override fun onResponse(call: Call<String>?, response: Response<String>?) {
val responseBody = response?.body() ?: ""
Log.e("retrofitnya","response body as string = ${responseBody}")
}
(If we want to use it as Users after that) do manually de-serialize it.
val user: Users = Gson().fromJson(responseBody, Users::class.java)
If it is not too confidential, plz give us how you declare that Users data object like, for example, this Foo and Bar.
data class Foo(
#SerializedName("bar") val bar: Bar?
)
data class Bar(
#SerializedName("name") val name: String?
)
I solved this by myself, actually its my silly miss understanding which is that end point is wrong.
In my wrong code
object DataRepository {
fun create(): RetrofitInstance {
val retrofit = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("https://github.com")
.build()
return retrofit.create(RetrofitInstance::class.java)
}
}
That wrong end point is
https://github.com
The true one is
https://api.github.com/