Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
308 views
in Technique[技术] by (71.8m points)

android - How can I get data from response body?

I need to get "status" value from my response. I tried JSONObject but it gave that java.lang.reflect.InvocationTargetException error in the code below. I need that because I make some process with status value like start new activity etc. How can I get this?

private fun doReq(){
    val client = OkHttpClient().newBuilder()
        .build()
    val mediaType = "application/json;charset=utf-8".toMediaTypeOrNull()
    val body: RequestBody = jsonSended.toRequestBody(mediaType)
    val request: Request = Request.Builder()
        .url("https://apiapiapi/auth")
        .method("POST", body)
        .addHeader("Content-Type", "application/json")
        .addHeader("Authorization", "$authValue")
        .addHeader("x-iyzi-rnd", "$randomString")
        .addHeader("cache-control", "no-cache")
        .build()

    val response = client.newCall(request).execute()
    println(response.body?.string())  // I CAN GET RESPONSE BODY 

    var json = JSONObject(response.body.toString())
    var status = json.getString("status")  // HERE NOT WORKING...

    println(status)


}

In the response when server return failure : {"status":"failure","errorCode":"12","errorMessage":"invalid","locale":"tr","systemTime":1610022545347,"conversationId":"123412341234"}

If server return valid my response is very very long but it also have status so I can get that status value and do something with that. Is that correct way to do it? I need advice.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use response.response or make request in try catch block statement, it will solve the problem


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...