Sunday, 16 July 2017

Volley POST Request Body

This happens whenever web services requesting data through json body . Below is the code example of using json volley request with body :

/*Some example that you can pass your data through request body*/RequestQueue requestQueue = Volley.newRequestQueue(this);
JSONObject jsonBodyObj = new JSONObject();
String url = "https://api.webempath.net/v2/analyzeWav";
try{
    jsonBodyObj.put("key1", "value");
    jsonBodyObj.put("key2", "value");
}catch (JSONException e){
    e.printStackTrace();
}
final String requestBody = jsonBodyObj.toString();

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
        url, null, new Response.Listener<JSONObject>(){
    @Override    public void onResponse(JSONObject response) {
        Log.i("Response",String.valueOf(response));
    }
}, new Response.ErrorListener() {
    @Override    public void onErrorResponse(VolleyError error) {
        VolleyLog.e("Error: ", error.getMessage());
    }
}){
    @Override    public Map<String, String> getHeaders() throws AuthFailureError {
        HashMap<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json");
        return headers;
    }


    @Override    public byte[] getBody() {
        try {
            return requestBody == null ? null : requestBody.getBytes("utf-8");
        } catch (UnsupportedEncodingException uee) {
            VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
                    requestBody, "utf-8");
            return null;
        }
    }


};

requestQueue.add(jsonObjectRequest);




No comments:

Post a Comment