Reputation: 1
enter image description hereI'm trying to make a POST request to my API and it works in Postman (I get a valid JSON object), but not using Volley. With the following code:
response in pdf format .Where I did the mistake can anyone help me
class PayslipActivity : Activity() {
var financialyear: Spinner? = null
var month: Spinner? = null
var emp_num: String? = null
var msg: String? = null
var statusCode = 0
var preview: Button? = null
var download: Button? = null
var progressBar: ProgressBar? = null
var stringArrayList: ArrayList<String?> = ArrayList()
var monthArrayList: ArrayList<String?> = ArrayList()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_payslip)
val toolbartitle: TextView = findViewById<TextView>(R.id.txt_toolbar_title)
toolbartitle.setText("My PaySlip")
stringArrayList.add("2023")
stringArrayList.add("2024")
progressBar = findViewById(R.id.progressBar)
financialyear = findViewById(R.id.financial_year)
month = findViewById(R.id.month)
monthArrayList.add("5")
monthArrayList.add("6")
preview = findViewById(R.id.btn_preview)
val adapter1 = ArrayAdapter(
applicationContext,
android.R.layout.simple_dropdown_item_1line,
stringArrayList
)
adapter1.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line)
financialyear!!.setAdapter(adapter1)
val adapter2 = ArrayAdapter(
applicationContext,
android.R.layout.simple_dropdown_item_1line,
monthArrayList
)
adapter2.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line)
month!!.setAdapter(adapter2)
financialyear?.setOnItemSelectedListener(object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>,
view: View,
position: Int,
id: Long
) {
(parent.getChildAt(0) as TextView).setTypeface(null, Typeface.BOLD)
Toast.makeText(applicationContext,financialyear!!.selectedItem.toString(),Toast.LENGTH_LONG).show()
}
override fun onNothingSelected(parent: AdapterView<*>?) {}
})
month?.setOnItemSelectedListener(object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>,
view: View,
position: Int,
id: Long
) {
(parent.getChildAt(0) as TextView).setTypeface(null, Typeface.BOLD)
}
override fun onNothingSelected(parent: AdapterView<*>?) {}
})
preview!!.setOnClickListener(View.OnClickListener {
submitdata(SharedPrefrence.getApiurl(applicationContext)
.toString() + "/api/v1/payroll/payslip")
})
}
fun submitdata(url: String?) {
progressBar!!.visibility = View.VISIBLE
//new HttpsTrustManager().allowAllSSL();progressBar.setVisibility(View.VISIBLE);
val js = JSONObject()
val jsonObj = JSONObject()
try {
js.put("year", financialyear!!.selectedItem.toString())
js.put("month",month!!.selectedItem.toString())
js.put("exp_number", emp_num)
} catch (e: JSONException) {
e.printStackTrace()
}
val JsonObjectRequest = object : JsonObjectRequest(
Request.Method.POST, url, js,
Response.Listener { response ->
val pdfUrl = response.getString("pdfUrl") // Assuming the response contains a PDF URL
fetchPdf(applicationContext, pdfUrl)
Toast.makeText(this@PayslipActivity, response.toString(), Toast.LENGTH_LONG).show()
},
Response.ErrorListener {error ->
Log.e("Volley", "Error: $error")
Toast.makeText(this@PayslipActivity, error.toString(), Toast.LENGTH_LONG).show()
if (error is VolleyError && error.networkResponse != null) {
val statusCode = error.networkResponse.statusCode
if (statusCode == 400) {
// Handle 400 error specifically
Log.e("Volley", "Bad Request: ${error.message}")
// Provide user-friendly error message
}
}
}) {
@Throws(AuthFailureError::class)
override fun getHeaders(): Map<String, String> {
val headers = HashMap<String, String>()
headers["Authorization"] = "Bearer " + SharedPrefrence.getApitoken(applicationContext)
headers["x-api-key"] = SharedPrefrence.getApikey(applicationContext)!!
headers["Content-Type"] = "application/x-www-form-urlencoded; charset=utf-8"
return headers
}
override fun getBodyContentType(): String {
return "application/json";
}
}
JsonObjectRequest.retryPolicy = DefaultRetryPolicy(
100000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
)
val requestQueue = Volley.newRequestQueue(this)
requestQueue.add(JsonObjectRequest)
}
@SuppressLint("ServiceCast")
private fun fetchPdf(context: Context, pdfUrl: String) {
val downloadManager = applicationContext.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
val request = DownloadManager.Request(Uri.parse(pdfUrl)).setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI or DownloadManager.Request.NETWORK_MOBILE)
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
"payslip.pdf")
val downloadId = downloadManager.enqueue(request)
// Register a broadcast receiver to listen for download completion
// ...
// Once download is complete (e.g., in a broadcast receiver):
val intent = Intent(Intent.ACTION_VIEW)
intent.setDataAndType(Uri.fromFile(File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
"payslip.pdf")), "application/pdf")
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
context.startActivity(intent)
}
}
I get the following error: 02-12 21:42:54.774: E/Volley(19215): [46574] BasicNetwork.performRequest: Unexpected response code 400 for http://somename/token/
Upvotes: 0
Views: 23