I am creating an android application using Co-WIN Public APIs.
I am using API for authentication using mobile and OTP.
send OTP work fine but confirm OTP, not working.
I am using volley to confirm OTP.
https://cdn-api.co-vin.in/api/v2/auth/public/confirmOTP/*
this is my code
val url ="https://cdn-api.co-vin.in/api/v2/auth/public/confirmOTP/"
val params = HashMap<String, String>()
params["otp"] = otp
params["txnId"] = txnID
params["Content-Type"] = "application/json"
params["accept"] = "application/json"
val jsonObjectRequest = object : JsonObjectRequest(
Request.Method.POST, url, JSONObject(params as Map<*, *>),
{ response ->
Log.d("verify otp", "opt success ${response.getString("token")}")
},
{ it ->
Log.d("faild request", "opt error ${it.localizedMessage}")
}){
override fun getParams(): Map<String, String> {
val params: MutableMap<String, String> = HashMap()
params["otp"] = otp
params["txnId"] = txnID
return params
}
#Throws(AuthFailureError::class)
override fun getHeaders(): Map<String, String> {
val params = HashMap<String, String>()
params["otp"] = otp
params["txnId"] = txnID
params["Content-Type"] = "application/json"
params["accept"] = "application/json"
return params
}
I am getting this error.
E/Volley: [799] NetworkUtility.shouldRetryException: Unexpected response code 401
for https://cdn-api.co-vin.in/api/v2/auth/public/confirmOTP/
Related
I'm trying to send a Firebase Cloud message with Volley, but the code below gives an error:
Error: Volley: [82541] NetworkUtility.shouldRetryException: Unexpected response code 400 for https://fcm.googleapis.com/fcm/send.
I tried it with Retrofit. but I need to do it with Volley.
Hope you can help. Thanks.
val url = "https://fcm.googleapis.com/fcm/send"
val request = object : StringRequest(Method.POST,url, Response.Listener { reply ->
}, Response.ErrorListener { error -> }){
override fun getParams(): MutableMap<String, String> {
val params = HashMap<String,String>()
params["to"] = "/topics/topic-subs"
params["title"] = "test volley title"
params["message"] = "test volley message"
return params
}
override fun getHeaders(): MutableMap<String, String> {
val params = HashMap<String,String>()
params["Authorization"] = "key="+"AAAAz6NjPJA:xxxxx"
params["Content-Type"] = "application/json; charset=utf-8"
return params
}
}
Volley.newRequestQueue(this#MainActivity).add(request)
I am using the code in this tutorial
Upload an Image or File to Your Server Using Volley in Kotlin
The code works I can upload an image but I also need to post other values together with the image in the same request.
Following is the code which perform the upload. How do I add the other post values to the request?
private fun uploadImage() {
imageData?: return
val request = object : VolleyFileUploadRequest(
Method.POST,
postURL,
Response.Listener {
println("response is: $it")
},
Response.ErrorListener {
println("error is: $it")
}
) {
override fun getByteData(): MutableMap<String, FileDataPart> {
var params = HashMap<String, FileDataPart>()
params["imageFile"] = FileDataPart("image", imageData!!, "jpeg")
return params
}
}
Volley.newRequestQueue(this).add(request)
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("api_token", "gh659gjhvdyudo973823tt9gvjf7i6ric75r76");
params.put("name", mNameInput.getText().toString());
params.put("location", mLocationInput.getText().toString());
params.put("about", mAvatarInput.getText().toString());
params.put("contact", mContactInput.getText().toString());
return params;
}
I'm doing a post call to my OAUTH2 authentication with Android, trying to recibe my Bearer Token.
I'm using Kotlin language and i'm doing the post request with Volley.
The problem is that when i do my post request with Postman, it work's perfect, but when i do it in the same way using Volley post, my API REST yells: Invalid Request Exception, missing grant type.
And my android yells: Unexpected response code 400 for http://192.168.1.254:8081/oauth/token
Android call:
private fun loginUser() {
var grant_type = "password"
var username = etUsername.text.toString()
var password = etPassword.text.toString()
val credentials = "angularapp"+":"+"12345"
// Post parameters
// Form fields and values
val params = HashMap<String,String>()
params["grant_type"] = grant_type
params["username"] = username
params["password"] = password
val jsonObject = JSONObject(params)
val request = CustomJsonObjectRequestBasicAuth(Request.Method.POST, Network.API_URL_LOGIN,jsonObject,
Response.Listener{ response->
Log.d("RESPONSEEEE", response.toString())
try {
// Parse the json object here
Log.d("Response" ,response.toString())
val intent = Intent(this, PatientsActivity::class.java)
intent.putExtra(Tags.FLOOR.toString(), ((spiFloor?.selectedItemId!!+1)))
startActivity(intent)
}catch (e:Exception){
e.printStackTrace()
}
}, Response.ErrorListener{
Log.d("ERROR", "VOLLEY ERROR")
},credentials
)
// Add the volley request to request queue
VolleySingleton.getInstance(this).addToRequestQueue(request)
}
// 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/x-www-form-urlencoded"
val auth = "Basic " + Base64.encodeToString(mCredentials.toByteArray(), Base64.NO_WRAP)
headers["Authorization"] = auth
System.out.println(headers.toString())
return headers
}
}
I have the following request on Insomnia:
Which is working fine!
But, if I try to do this on Android with volley I get a "ServerError":
fun createRequest() {
val params = JSONObject()
params.put("device_key", Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID))
params.put("edition_date", "2018-02-12 00:00:00")
params.put("publication", 1)
val headers = hashMapOf<String, String>()
headers["Authorization"] = "My Token"
headers["Content-Type"] = "application/x-www-form-urlencoded"
getPDF(this, params, headers)
}
fun getPDF(activity: Activity, params: JSONObject, headers: HashMap<String, String>) {
val request = object : JsonObjectRequest(Request.Method.POST, "My URL", params,
Response.Listener {
print("asd")
},
Response.ErrorListener {
it.printStackTrace()
}
) {
override fun getHeaders(): Map<String, String> { return headers } }
request.retryPolicy = DefaultRetryPolicy(0, DEFAULT_MAX_RETRIES, DEFAULT_BACKOFF_MULT)
Volley.newRequestQueue(activity).add(request)
}
I'm only getting a "ServerError" with a code 500.
What could I be doing wrong in Android? Am I not settings the header correctly? Or could be the params?
In Insomnia you are making a request and the body is a form, while in Android you are trying to send a JSON. Make sure your body consists of key-value pairs and not a JSON object.
I am trying to make a post request to a web server I made but Volley keeps on sending a empty request with no data resulting in a 500 error.
val queue = Volley.newRequestQueue(this)
val jsonParams: MutableMap<String?, String?> =
HashMap()
jsonParams["STATUS"] = "on"
val myRequest: JsonObjectRequest = object : JsonObjectRequest(Method.POST, "http://example.com/url_to_post_to/", JSONObject(
jsonParams as Map<String, String>
), Response.Listener { response -> botStatus.text = response.toString() }, Response.ErrorListener { error -> print("There was a error!") }) {
#Throws(AuthFailureError::class)
override fun getHeaders(): Map<String, String> {
val headers =
HashMap<String, String>()
headers["Content-Type"] = "application/json; charset=utf-8"
//headers["User-agent"] = "My useragent"
return headers
}
}
queue.add(myRequest)
Any help would be greatly appreciated.
Okay, I figured out what the problem was. My server didn't accept JSON payload requests. I have switched to using the Fuel library now as well.