Thursday 27 September 2018

Android Volley post request for x-www-form-urlencoded

Hi, in post API link there are a few type, which is include form-data, x-www-form-urlencoded, raw and binary......

this tutorial code will show your how to post API link for x-www-form-urlencoded

private void postFunction(){

     RequestQueue requestQueue;
     Cache cache = new DiskBasedCache(getCacheDir(),1024*1024);
     Network network = new BasicNetwork(new HurlStack());
     requestQueue = new RequestQueue(cache, network);
     requestQueue.start();

      String apiLink = "";

      StringRequest jsonObjRequest = new StringRequest(Request.Method.POST, apiLink,
             new Response.Listener<String>() {
                 @Override
                 public void onResponse(String response) {
                     String s;
                     s = response.toString().trim();
                     JSONObject obj = null;
                         try {
                             obj = new JSONObject(s);
                         } catch (Throwable t) {
                         }
                          try {
                             String a = obj.getString("status");
                         } catch (JSONException e) {
                             e.printStackTrace();
                         }
                 }
             }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
             VolleyLog.d("volley", "Error: " + error.getMessage());
             error.printStackTrace();
          }     }) {

        @Override
        public String getBodyContentType() {
             return "application/x-www-form-urlencoded; charset=UTF-8";
         }

        @Override
        protected Response<String> parseNetworkResponse(NetworkResponse response) {
             String parsed;
             try {
                 parsed = new String(response.data, "UTF-8");
             } catch (UnsupportedEncodingException e) {
                 parsed = new String(response.data);
             }
             return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
         }

        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
             Map<String, String> params = new HashMap<String, String>();
             params.put("username", "nameTesting");
                          return params;
         }
     };

     requestQueue.add(jsonObjRequest);
 }

No comments:

Post a Comment