Loopj AsyncHttpClient JsonHttpResponseHandler not getting a timeout exception

550 Views Asked by At

I am trying to connect to a server using following code. However I am not able to get a timeout even after switching off the server. I want to know where i am going wrong.

However I do get call to onFinish function. But not being able to distinguish if it is because of completing the request successfully or some other reason.

I want to know why i am not getting timeouts and how do i change my code to implement a function to handle the timeout while server is down.

 fun getJSONData() {

        Toast.makeText(this@LoginActivity, " Starting to Get Data", Toast.LENGTH_LONG).show()

        val client = AsyncHttpClient()
        client.addHeader("X-Csrf-Token", "fetch")
        client.addHeader("Accept", "application/json")
        client.setBasicAuth("userid", "pwd")
        client.responseTimeout = 1000
        client.setTimeout(1000)
        client.connectTimeout = 1000

        Toast.makeText(this@LoginActivity, "---->" + client.connectTimeout + ':' + client.responseTimeout, Toast.LENGTH_LONG).show()

        client.get(getURL, object : JsonHttpResponseHandler() {

            override fun onSuccess(statusCode: Int, headers: Array<out Header>, response: JSONObject) {

                super.onSuccess(statusCode, headers, response)

              // do further processing

            }

            override fun onFailure(statusCode: Int, headers: Array<out Header>?, responseString: String?, throwable: Throwable?) {

                super.onFailure(statusCode, headers, responseString, throwable)

            }

            override fun onFinish() {
                super.onFinish()


            }

            override fun onRetry(retryNo: Int) {
                super.onRetry(retryNo)
            }
        })
    }
2

There are 2 best solutions below

1
Mubeen On BEST ANSWER

We implemented overriding function of onFailure with different parameters and worked like charm.

Replace this code

override fun onFailure(statusCode: Int, headers: Array<out Header>?, responseString: String?, throwable: Throwable?) {

            super.onFailure(statusCode, headers, responseString, throwable)

        }

with this

override fun onFailure(statusCode: Int, headers: Array<out Header>?, responseString: String?, throwable: Throwable?) {

                super.onFailure(statusCode, headers, responseString, throwable)

            }

We discovered this by going through logcat errors of this application which expected the second function to be implemented.

1
Rendra_HMD On

This one was worked for me

 try {
                URL url = new URL(sUrl);
                HttpURLConnection connection = (HttpURLConnection)url.openConnection(); 
                connection.setConnectTimeout(iConnectTimeout); //default 9999ms
                connection.setReadTimeout(iReadTimeout);    // def 9999
                connection.setRequestMethod(sMethod);