2

I want to send this json body to server using POST METHOD

{"device_type": "SUP","commands": [

{

  "command_id": 165,

  "arguments": [

    {

      "name": "Host",

      "value": "google.com"

    }

  ]

}]}

I tried many solutions available on web but most of them tell to format the string and sent to server. Is there any correct way to send this body to server end using volley. please help me. Thanks.

3 Answers 3

7

Let's start from the bottom. First,

JSONObject json1= new JSONObject();
json1.put("name","Host");
json1.put("value","google.com");

After this we put the above object inside an array

JSONArray jsonArray = new JSONArray();
jsonArray.put(json1);

Now we add the above array and command id to a new object

JSONObject json2= new JSONObject();
json2.put("command_id","165");
json2.put("arguments",jsonArray);

Again this is an object of commands array

JSONArray jsonArray2 = new JSONArray();
jsonArray2.put(json2);

Now we put the above array and device type inta a final object

JSONObject json3= new JSONObject();
json3.put("device_type","SUP");
json3.put("commands",jsonArray2);

Now you can convert json3 object to string and send to server.

json3.toString;
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome explanation @Nirup Iyer Thanks for your time :)
0

create a JSONObject json = new JSONObject(device_type(in your case)) for the json data you would like and post it to volley

1 Comment

Thanks for reply .But how to send array ie arguments .
0

You can use this class:

public class GsonRequest<T> extends Request<T> {

    public static final String HEADER_CONTENT_TYPE = "Content-Type";
    public static final String CONTENT_TYPE_TEXT_HTML = "text/html";
    public static final int HTTP_STATUS_OK = 200;

    protected final Type mTypeOfT;
    private final Response.Listener<T> mListener;
    protected final Gson mGson;
    protected String mUrl = "";

    protected boolean mIsCached = false;

    /**
     * Create a new Gson Json-parser request.
     *
     * @param method the Http method see {@link com.android.volley.Request.Method}
     * @param typeOfT type of generic.
     * @param url request url.
     * @param listener response listener.
     * @param errorListener error listener.
     */
    public GsonRequest (final int method, final Type typeOfT, final String url,
    final Response . Listener < T > listener,
    final Response . ErrorListener errorListener) {
        this(method, typeOfT, url, listener, errorListener, new Gson ());
    }

    /**
     * Create a new Gson Json-parser request with a custom gson instance (useful for specifying
     * custom date formats, etc.)
     *
     * @param method the Http method see {@link com.android.volley.Request.Method}
     * @param typeOfT type of generic.
     * @param url request url.
     * @param listener response listener.
     * @param errorListener error listener.
     * @param gson custom Gson instance.
     */
    public GsonRequest (final int method, final Type typeOfT, final String url,
    final Response . Listener < T > listener,
    final Response . ErrorListener errorListener, final Gson gson) {
        super(method, url, errorListener);

        mListener = listener;
        mTypeOfT = typeOfT;
        mGson = gson;
        mUrl = url;
    }



    @Override
    protected Response < T > parseNetworkResponse (final NetworkResponse response) {
        try {

            String charset = HttpHeaderParser . parseCharset (response.headers);
            Log.d("response", "1");
            final String responseData = new String (response.data, charset);
            Log.d("response", "2");
            logResponse("Request finished with response from the server:", response, responseData);

            if (isHtmlFacade(response)) {

                return Response.error(new VolleyError ());
            }

            T responseObject;
            if (responseData.startsWith("{\"list\":")) {
                Log.d("response", "if");
                String json = responseData . substring (responseData.indexOf(":") + 1, responseData.indexOf("]")+1);


                responseObject = mGson.fromJson(json, mTypeOfT);
            } else {
                Log.d("response-single", responseData);
                responseObject = mGson.fromJson(responseData, mTypeOfT);
            }


            return Response.success(responseObject, HttpHeaderParser.parseCacheHeaders(response));
        } catch (Exception e) {

            return Response.error(new ParseError (e));
        }
    }


    /**
     * @param response the response to check
     * @return true if the response contains html according to its Content-Type and the status is
     * 200 OK.
     */
    private boolean isHtmlFacade(NetworkResponse response) {
        Map<String, String> headers = response . headers;
        String contentType = headers . get (HEADER_CONTENT_TYPE);

        return response.statusCode == HTTP_STATUS_OK && contentType != null
                && contentType.contains(CONTENT_TYPE_TEXT_HTML);
    }

    @Override
    protected void deliverResponse(final T response) {
        mListener.onResponse(response);
    }
}

And then call:

GsonRequest<Model> request = new GsonRequest<Model>(Request.Method.POST,Model.class,"http://requestUrl", onsuccessListener, onerrorListener)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.