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.
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 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/
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 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 have the following onCreate class in MainActivity and proven to be able to work with my server. It is able to extract out the JWT token
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
submitButton = findViewById<Button>(R.id.btn_submit)
// Volley code is here
val url = "http://192.168.1.8:4000"
submitButton.setOnClickListener({
val pinCode = pin_code.text.toString()
queue = Volley.newRequestQueue(this)
val params = HashMap<String, String>()
params.put("pin_code", pinCode)
val request = object : JsonObjectRequest(Request.Method.POST, url + "/api/employees/token", JSONObject(params),
Response.Listener<JSONObject> { response ->
val token = response
.getJSONObject("data")
.getString("token")
val myIntent = Intent(this, SiteActivity::class.java)
startActivityForResult(myIntent, 0)
},
Response.ErrorListener {
Toast.makeText(this, "That didn't work!", Toast.LENGTH_SHORT).show()
}){
#Throws(AuthFailureError::class)
override fun getHeaders(): MutableMap<String, String> {
val headers = HashMap<String, String>()
headers.put("Accept", "application/json")
headers.put("Content-Type", "application/json; charset=utf-8")
return headers
}
}
queue.add(request)
queue.start()
})
}
Unfortunately I have not figured out a way to add the JWT token into the authorized bearer Header for the next SiteActivity. Any suggestion how to make this work? Should I pass the token directly to the next activity or should I use a singleton? Thanks!
Straightly answering question
Put data into Intent with putExtra("token", token).
Take it on the other side with getIntent().getStringExtra("token").
But...
You may want to save token persistently. For example, into SharedPreferences.