Surinder Singh
Surinder Singh

Reputation: 35

how to post json array object on server using volley library in android..?

Hello i want post this [{"name":"fdfdfdfdfdfdfsdfsdfsdf"}] simple array on server. Im using the volley libray, request method is POST, Dataformat is array,

can anyone explain me to to do it ..?

Upvotes: 0

Views: 830

Answers (1)

samuel githae
samuel githae

Reputation: 15

This worked for me 1. Create a new java class

    package com.hudutech.hakiki.hfarm;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;

/**
 * Created by New LAptop on 10/03/2017.
 */
public class JsonPostArrayRequest extends JsonRequest<JSONObject> {

    JSONArray params;
    public JsonPostArrayRequest(String url,JSONArray params, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
        super(Method.POST, url, null, listener, errorListener);
        this.params=params;
    }

    @Override
    public byte[] getBody()  {
        if ( this.params != null && this.params.length() > 0) {
            return encodeParameters( this.params, getParamsEncoding());
        }
        return null;

    }

    private byte[] encodeParameters(JSONArray params, String paramsEncoding) {
        try {
            return params.toString().getBytes(paramsEncoding);
        } catch (UnsupportedEncodingException uee) {
            throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee);
        }
    }

    @Override
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString =
                    new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            return Response.success(new JSONObject(jsonString),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }
}
  1. Call the class where you want to post the array

    JsonPostArrayRequest req = new JsonPostArrayRequest(Paths.register_animal_url,obj, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            //Toast.makeText(getApplicationContext(), response.getString("message")+poultry_kind, Toast.LENGTH_LONG).show();
            dialog.hide();
           try{
            Toast.makeText(getApplicationContext(), response.getString("message"), Toast.LENGTH_LONG).show();
            VolleyLog.v("Response:%n %s", response.toString(4));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        }
    
    
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            // Handle error
            VolleyLog.e("Error: ", volleyError.getMessage());
            String message = null;
            if (volleyError instanceof NetworkError) {
                message = "Cannot connect to Internet...Please check your connection!";
            } else if (volleyError instanceof ServerError) {
                message = "The server could not be found. Please try again after some time!!";
            } else if (volleyError instanceof AuthFailureError) {
                message = "Cannot connect to Internet...Please check your connection!";
            } else if (volleyError instanceof ParseError) {
                message = "Parsing error! Please try again after some time!!";
            } else if (volleyError instanceof NoConnectionError) {
                message = "Cannot connect to Internet...Please check your connection!";
            } else if (volleyError instanceof TimeoutError) {
                message = "Connection TimeOut! Please check your internet connection.";
            }
            Toast.makeText(getApplicationContext(), message,Toast.LENGTH_LONG).show();
            dialog.dismiss();
        }
    });
    

    MySingleton.getInstance(getApplicationContext()).addToRequeue(req);

It may be a late answer but may help someone.

Upvotes: 1

Related Questions