0

I'm trying to send a POST request using Kotlin in Android. I need to use Volley and I need authentication with a bearer token. I don't know how to send the bearer token together with the post request.

val queue = Volley.newRequestQueue(this)

val parameters: MutableMap<String, String> = HashMap()

parameters.put("token_name", "app");

val strReq: StringRequest = object : StringRequest(
    Method.POST, "https://url.com",
    Response.Listener { response ->

 try {

 val responseObj = JSONObject(response)

 val id = responseObj.getInt("id")
 val token = responseObj.getString("name")
 val tipo = responseObj.getString("email")

 } catch (e: Exception) { // caught while parsing the response

}

},
Response.ErrorListener { volleyError ->

})
Josh
  • 485
  • 2
  • 11
  • 22

1 Answers1

1

You can override the volley's request method:

public void requestWithSomeHttpHeaders(Context context) {
        RequestQueue queue = Volley.newRequestQueue(context);
        String url = "http://www.somewebsite.com";
        StringRequest getRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        // response
                        try {
                            JSONObject responseObj = new JSONObject(response);
                            int id = responseObj.getInt("id");
                            String token = responseObj.getString("name");
                            String tipo = responseObj.getString("email");

                        } catch (Exception e) { // caught while parsing the response

                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // TODO Auto-generated method stub
                        Log.d("ERROR", "error => " + error.toString());
                    }
                }
        ) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                //insert your bearer token here
                params.put("bearer token", "xxxxxx");
                return params;
            }
        };
        queue.add(getRequest);
    }

Of course, you can read this post as a refer.

penkzhou
  • 1,200
  • 13
  • 30