MainActivity.kt
package com.cfsuman.kotlintutorials
import android.app.Activity
import android.os.Bundle
import android.widget.*
import com.android.volley.Request
class MainActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// get the widgets reference from XML layout
val button = findViewById<Button>(R.id.button)
val textView = findViewById<TextView>(R.id.textView)
// Run volley
button.setOnClickListener {
// Disable the button itself
it.isEnabled = false
//val credentials = "username:$password"
val credentials = "postman:password"
val url = "https://postman-echo.com/basic-auth"
textView.text = ""
// Make a volley custom json object request
// with basic authentication
val request = CustomJsonObjectRequestBasicAuth(
Request.Method.GET, url,null,
{ response->
try {
// Parse the json object here
textView.text = "Response : $response"
}catch (e:Exception){
e.printStackTrace()
textView.text = "Parse exception : $e"
}
}, {
textView.text = "Volley error: $it}"
},credentials
)
// Add the volley request to request queue
VolleySingleton.getInstance(this)
.addToRequestQueue(request)
}
}
}
CustomJsonObjectRequestBasicAuth.kt
package com.cfsuman.kotlintutorials
import android.util.Base64
import com.android.volley.AuthFailureError
import com.android.volley.Response
import com.android.volley.toolbox.JsonObjectRequest
import org.json.JSONObject
// Class to make a volley json object request
// with basic authentication
class CustomJsonObjectRequestBasicAuth(
method:Int, url: String,
jsonObject: JSONObject?,
listener: Response.Listener<JSONObject>,
errorListener: Response.ErrorListener,
credentials:String
)
: JsonObjectRequest(
method,url, jsonObject, listener, errorListener) {
private var mCredentials:String = credentials
@Throws(AuthFailureError::class)
override fun getHeaders(): Map<String, String> {
val headers = HashMap<String, String>()
headers["Content-Type"] = "application/json"
//val credentials:String = "username:password"
val auth = "Basic " + Base64.encodeToString(
mCredentials.toByteArray(),
Base64.NO_WRAP)
headers["Authorization"] = auth
return headers
}
}
VolleySingleton.kt
package com.cfsuman.kotlintutorials
import android.content.Context
import com.android.volley.Request
import com.android.volley.RequestQueue
import com.android.volley.toolbox.Volley
class VolleySingleton constructor(context: Context) {
companion object {
@Volatile
private var INSTANCE: VolleySingleton? = null
fun getInstance(context: Context) =
INSTANCE ?: synchronized(this) {
INSTANCE ?: VolleySingleton(context).also {
INSTANCE = it
}
}
}
private val requestQueue: RequestQueue by lazy {
// applicationContext is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
Volley.newRequestQueue(context.applicationContext)
}
fun <T> addToRequestQueue(req: Request<T>) {
requestQueue.add(req)
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#DCDCDC"
android:padding="24dp">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Run Volley"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginTop="16dp"
android:fontFamily="sans-serif"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button"
tools:text="TextView" />
</androidx.constraintlayout.widget.ConstraintLayout>
gradle dependencies
// Volley network library
implementation 'com.android.volley:volley:1.2.1'