API Request

This is an example for the usage of API Request with OkHttp in a kotlin Android applications.


build.gradle

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
    .............
}
dependencies {
    .........
    implementation 'com.squareup.okhttp3:okhttp:3.9.1'    .........
}

AppConstants.kt

object AppConstants {
    object APIURLS {
        val REGISTER = "https://example.com/register"
        val LOGIN = "https://example.com/login"    }
    object APICode {
        val REGISTER = 1        val LOGIN = 2    }

    object RequestDataKey {
        //---------REGISTER---------        val USER_NAME_SIGN_UP = "email"        val PASSWORD_SIGN_UP = "password"
        //---------LOGIN---------        val USER_NAME_SIGN_IN = "userId"        val PASSWORD_SIGN_IN = "password"    }
}


ApiResponse.kt

interface ApiResponse {
    fun apiResponsePostProcessing(response: String, apiCode: Int)
    fun networkError(apiCode: Int)
    fun responseError(responseError: String, apiCode: Int)
    fun responseError(responseError: String, successedUrlList: ArrayList<Int>, apiCode: Int)
}
 

NetworkUtility.kt

object NetworkUtility {

    private val MEDIA_TYPE_PNG = MediaType.parse("image/png")
    private val MEDIA_TYPE_JPEG = MediaType.parse("image/jpeg")
    private val MEDIA_TYPE_JPG = MediaType.parse("image/jpg")
    private val JSON = MediaType.parse("application/json; charset=utf-8")
    fun isConnectivityAvailable(context: Context?): Boolean {
        val connectivityManager = context!!.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

        val activeNetwork = connectivityManager.activeNetworkInfo        return activeNetwork != null && activeNetwork.isConnectedOrConnecting    }
    @Throws(IOException::class)
    fun getOkHttpClient(request: Request): String
    {
        val client = OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .build()

        val response = client.newCall(request).execute()
        return response.body()!!.string()
    }
    @Throws(IOException::class)
    fun getResponseWithGet(url: String?) : String
    {
        Log.d("Url--->",url)

        val request = Request.Builder()
                .url(url)
                .build()

        return getOkHttpClient(request)
    }
    @Throws(IOException::class)
    fun getResponseWithPost(url: String?,postDataParams : HashMap<String, String>) : String
    {

        Log.d("Url--->",url)

        val fromBodyBuilder = FormBody.Builder()
        for (entry in postDataParams) {
            Log.d("param--->", entry.key + ":" + entry.value)
            fromBodyBuilder.add(entry.key,entry.value)
        }

        val request = Request.Builder()
                .url(url)
                .post(fromBodyBuilder.build())
                .build()

        return getOkHttpClient(request)

    }
    @Throws(IOException::class)
    fun getResponseWithPostImages(url: String?,postDataParams : HashMap<String, String>,files:ArrayList<File>) : String
    {

        Log.d("Url--->",url)
        val multipartBuilder = MultipartBody.Builder()
        multipartBuilder.setType(MultipartBody.FORM)

        for (entry in postDataParams) {
            Log.d("param--->", entry.key + ":" + entry.value)
            multipartBuilder.addFormDataPart(entry.key, entry.value)
        }
        var index = 0        for (files_details in files) {
            ++index
            Log.d("file--->", "("+index+") fileName:"+files_details.name+" filepath:"+files_details.path)
            multipartBuilder.addFormDataPart("image"+index, files_details.name, RequestBody.create(MEDIA_TYPE_PNG, files_details))
        }
        val request = Request.Builder()
                .url(url)
                .post(multipartBuilder.build())
                .build()

        return getOkHttpClient(request)

    }
    @Throws(IOException::class)
    fun getResponseWithPostJson(url: String?,jsonBody:String?) : String
    {
       
        Log.d("Url--->",url)

        Log.d("jsonBody--->",jsonBody)
        val body = RequestBody.create(JSON, jsonBody)

        val request = Request.Builder()
                .url(url)
                .post(body)
                .build()

        return getOkHttpClient(request)
    }
}
 

BackgroundAsyncTask.kt

class BackgroundAsyncTask : AsyncTask<Any, Void, String> {

    private var context: Context? = null    private var url: String? = null    private var apiResponse: ApiResponse? = null    private var code: Int = 0    private var isGET: Boolean = false    private var isProgressBar: Boolean = false    private var isFile: Boolean = false    private var postDataParams = HashMap<String, String>()
    private var files = ArrayList<File>()
    private var alertDialogBuilder : AlertDialog.Builder? = null    private var alertDialog : AlertDialog? = null    constructor(context: Context?,isProgressBar:Boolean, url: String?, code: Int) {
        this.context = context
        this.url = url
        this.code = code
        this.isGET = true        this.isProgressBar = isProgressBar
        this.isFile = false    }

    constructor(context: Context?,isProgressBar:Boolean, url: String?, code: Int, postDataParams: HashMap<String, String>) {

        this.context = context
        this.url = url
        this.code = code
        this.isGET = false        this.isProgressBar = isProgressBar
        this.postDataParams = postDataParams
        this.isFile = false    }
    constructor(context: Context?,isProgressBar:Boolean, url: String?, code: Int, postDataParams: HashMap<String, String>,files:ArrayList<File>) {

        this.context = context
        this.url = url
        this.code = code
        this.isGET = false        this.isProgressBar = isProgressBar
        this.postDataParams = postDataParams
        this.isFile = true        this.files = files
    }

    override fun onPreExecute() {
        //System.out.println("Request URL :"+url);        if (!NetworkUtility.isConnectivityAvailable(context)) {

            val alertDialogBuilder = AlertDialog.Builder(
                    context)
            alertDialogBuilder.setTitle("Connectivity")
            alertDialogBuilder.setMessage("Pleace check internet conection")
            alertDialogBuilder.setCancelable(false)

            alertDialogBuilder.setNegativeButton("ok") { dialog, which ->                dialog.dismiss()

                /*val activity = context as Activity?                activity!!.finish()*/            }
            alertDialogBuilder.setPositiveButton("ReTry") { dialog, which ->                if(isGET) {
                    BackgroundAsyncTask(context,isProgressBar, url, code).execute(context)
                }else                {
                    if(isFile)
                        BackgroundAsyncTask(context,isProgressBar, url, code, postDataParams,files).execute(context)
                    else                        BackgroundAsyncTask(context,isProgressBar, url, code, postDataParams).execute(context)
                }
            }
            alertDialogBuilder.show()

            this.cancel(true)
            return        }
        else        {
            if(isProgressBar) {
                alertDialogBuilder = AlertDialog.Builder(context)
                alertDialogBuilder!!.setTitle("Please wait...")
                alertDialogBuilder!!.setCancelable(false)
                var progressBar = ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal)
                progressBar!!.isIndeterminate = true                alertDialogBuilder!!.setView(progressBar)
                alertDialog = alertDialogBuilder!!.show()
            }
        }

    }

    override fun doInBackground(vararg arg0: Any): String? {

        apiResponse = arg0[0] as ApiResponse
        var response: String? = null
            if (isGET) {
                    response = NetworkUtility.getResponseWithGet(url)//get method            } else {
                if(isFile)
                    response = NetworkUtility.getResponseWithPostImages(url, postDataParams,files)//post method for params with file                else                    response = NetworkUtility.getResponseWithPost(url, postDataParams)//post method for params            }

        return response
    }

    override fun onPostExecute(response: String) {

        println("Response in ASYNC :" + response)
        if(alertDialog !=null)
        {
            if(alertDialog!!.isShowing)
            {
                alertDialog!!.dismiss()
            }
        }
        if(response == null) {
            val alertDialogBuilder = AlertDialog.Builder(
                    context)
            alertDialogBuilder.setTitle("Server Error")
            alertDialogBuilder.setMessage("We're sorry! The server encountered an internal error and was unable to complete your request. Please try again later.")
            alertDialogBuilder.setCancelable(false)
            alertDialogBuilder.setNegativeButton("ok") { dialog, which ->                dialog.dismiss()
                /*val activity = context as Activity?                activity!!.finish()*/            }
            alertDialogBuilder.setPositiveButton("ReTry") { dialog, which ->                if(isGET) {
                    BackgroundAsyncTask(context,isProgressBar, url, code).execute(context)
                }else                {
                    if(isFile)
                        BackgroundAsyncTask(context,isProgressBar, url, code, postDataParams,files).execute(context)
                    else                        BackgroundAsyncTask(context,isProgressBar, url, code, postDataParams).execute(context)
                }
            }
            alertDialogBuilder.show()
        }
        else        {
            apiResponse!!.apiResponsePostProcessing(response, code)
        }

    }


}

MainActivity.kt

class MainActivity : AppCompatActivity(), ApiResponse{

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setSupportActionBar(toolbar)

        //Example of call to login api
        val postDataParams = HashMap<String, String>()
        postDataParams!!.put(AppConstants.RequestDataKey.USER_NAME_SIGN_IN,"test")
        postDataParams!!.put(AppConstants.RequestDataKey.PASSWORD_SIGN_IN,"123")
BackgroundAsyncTask(this,true,AppConstants.APIURLS.LOGIN,AppConstants.APICode.LOGIN,postDataParams).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,this)

        //Example of call to register api
        val postDataParams2 = HashMap<String, String>()
        postDataParams2!!.put(AppConstants.RequestDataKey.USER_NAME_SIGN_UP,"test")
        postDataParams2!!.put(AppConstants.RequestDataKey.PASSWORD_SIGN_UP,"123")

        BackgroundAsyncTask(this,true,AppConstants.APIURLS.REGISTER,AppConstants.APICode.REGISTER,postDataParams2).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,this)

        
        
    }

    override fun apiResponsePostProcessing(response: String, apiCode: Int) {
        when (apiCode) {
            AppConstants.APICode.REGISTER -> {
                Log.d("REGISTER","REGISTER"+response);
                 // handle to response
            }
            AppConstants.APICode.LOGIN -> {
                Log.d("LOGIN","LOGIN"+response);
                 // handle to response
} } } override fun networkError(apiCode: Int) { } override fun responseError(responseError: String, apiCode: Int) { } override fun responseError(responseError: String, successedUrlList: ArrayList<Int>, apiCode: Int) { } }

Comments

Popular posts from this blog