How to fetch the JSON data from the Request body Nano HTTP session using Android Kotlin

44 Views Asked by At

I am using Nano httpD to fetch the request body. Most of the case its working fine. But some case its throwing null pointer exception as shown below.

enter image description here

I am using below method to fetch the json,

val test: Map<String, String> = HashMap()
            val method = session.method
            if (Method.PUT == method || Method.POST == method) {
                try {
                    session.parseBody(test)
                } catch (ioe: IOException) {
                    return newFixedLengthResponse(
                        Response.Status.INTERNAL_ERROR,
                        MIME_PLAINTEXT,
                        "SERVER INTERNAL ERROR: IOException: " + ioe.message
                    )
                } catch (re: ResponseException) {
                    return newFixedLengthResponse(re.status, MIME_PLAINTEXT, re.message)
                }
                catch (ex: Exception){
                    var ex = ex

                }
            }

I am hitting the nano httpd server with the request data, it has lines 500. I unable to read the request body.

So, i tried with the below method,

        val contentLength = session.headers["content-length"]!!.toInt()
            val buffer = ByteArray(contentLength)
            session.inputStream.read(buffer, 0, contentLength)

But i unable to convert this one to json data, since its it a byte array.

0

There are 0 best solutions below