skip to Main Content

I’m trying to make a get request to an API that returns a JSON array on android studio but when I check the logs it says that there was a problem… (I use kotlin by the way)

What did I do wrong?

here is my code:

val url = "http://example.com"
    val queue = Volley.newRequestQueue(context)

    val jsonArrayRequest = JsonArrayRequest(Request.Method.GET, url, null,
        {
            

            Log.d("notification", "successful request!")
        },
        {
            Log.d("notification", "error on request...")
        })

    queue.add(jsonArrayRequest)
}

2

Answers


  1. Chosen as BEST ANSWER

    After reading Techno World's answer I had an idea. Basically it's the same thing Techno World did but much easier. What I did is to print the response to the log like this:

    val url = "http://example.com"
    val queue = Volley.newRequestQueue(context)
    
    val jsonArrayRequest = JsonArrayRequest(Request.Method.GET, url, null,
        {
            Log.d("notification", "successful request!")
        },
        {response ->
            Log.d("notification", "error on request: $response")
        })
    
    queue.add(jsonArrayRequest)
    }
    

    So when I checked the log I saw this:

    error on request: com.android.volley.noconnectionerror: java.io.ioexception: cleartext http traffic to example.com not permitted
    

    After some research I found out that it was because I used http instead of https. So I changed it and it worked!

    Here is the original question on stack overflow about that error, there are more methods to solve it...


  2. var reqParam = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(userName, "UTF-8")
        reqParam += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8")
    
        val mURL = URL("<Yout API Link>?"+reqParam)
    
        with(mURL.openConnection() as HttpURLConnection) {
            // optional default is GET
            requestMethod = "GET"
    
            println("URL : $url")
            println("Response Code : $responseCode")
    
            BufferedReader(InputStreamReader(inputStream)).use {
                val response = StringBuffer()
    
                var inputLine = it.readLine()
                while (inputLine != null) {
                    response.append(inputLine)
                    inputLine = it.readLine()
                }
                it.close()
                println("Response : $response")
            }
        }
    

    Try this it will help solve your problem..

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search