Volley Post request ,Send Json object in Json array request
Asked Answered
C

5

6

To say in simple words i want to send this {"Id":7,"Name":"MyName"} data To server using Volley Post Request.

It has 1 integer and 1 String and response i get is Jsonarray

I tried Following ways but none are working

  • as it is json array request i cannot send data in argument as 3rd argument only takes JsonArray and i have to send JsonObject so kept it as null

    new JsonArrayRequest(Method,Url,JsonArray,ResponseListener,ErrorListner)

  • I cannot put it in HashMap as 1 of the value is integer, and it only accepts string

getparams() method

@Override
protected Map<String, String> getParams() throws AuthFailureError {
    Map<String,String> params=new HashMap<>();
    params.put("Id",7); //            <====== This is Invalid
    params.put("Name","MyName");
    return params;
}
  • I tried to send in getbody method ,still not working

getbody method

@Override
public byte[] getBody() {
    String body="{\"Id\":7,\"Name\":\"MyName\"}";
    return body.getBytes();
}

I can get the response using HttpUrlConnection.

Is there any other way to achieve it in volley ?

Cissie answered 21/4, 2017 at 10:34 Comment(0)
F
2

Seems like it was removed in recent volley version but you can easily modify this constructor and add to JsonArrayRequest.

public JsonArrayRequest(int method, String url, JSONObject jsonRequest,
                            Listener<JSONArray> listener, ErrorListener errorListener) {
        super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
                errorListener);
    }
Frissell answered 21/4, 2017 at 10:44 Comment(0)
C
6

Thanks to akash93 , i finally did it .Here is how to do it

write a class MyJsonArrayRequest.java like below

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;
public class MyJsonArrayRequest extends JsonRequest<JSONArray> {


    public MyJsonArrayRequest(int method, String url, JSONObject jsonRequest,
                              Response.Listener<JSONArray> listener, Response.ErrorListener errorListener) {
        super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
                errorListener);
    }

    @Override
    protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data,
                    HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
            return Response.success(new JSONArray(jsonString),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }

usage :

 MyJsonArrayRequest request=new MyJsonArrayRequest(Request.Method.POST, Constants.SEARCH_PROFILE, object, new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {

            Log.i("onResponse", ""+response.toString());
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
            Log.i("onErrorResponse", "Error");
        }
    });

even more easier way is to override getBody() which should work , but some way it didn't work for me first time.

 @Override
public byte[] getBody() {
    String body="{\"Id\":7,\"Name\":\"MyName\"}";
    return body.getBytes();
}
Cissie answered 31/8, 2017 at 10:10 Comment(1)
Thanks this works for me. I have to post JsonArrayRequest and response is as JsonObject.Jacquelinejacquelyn
F
2

Seems like it was removed in recent volley version but you can easily modify this constructor and add to JsonArrayRequest.

public JsonArrayRequest(int method, String url, JSONObject jsonRequest,
                            Listener<JSONArray> listener, ErrorListener errorListener) {
        super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
                errorListener);
    }
Frissell answered 21/4, 2017 at 10:44 Comment(0)
A
1
 JSONObject jsonObject = new JSONObject();
    try {
        // user_id, comment_id,status
        jsonObject.put("user_id", your_data);
        jsonObject.put("comment_id", your_data);
        jsonObject.put("status", your_data);
        jsonObject.put("token", your_data);
    } catch (Exception e) {
        e.printStackTrace();
    }

 JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
            YOUR_API _NAME, jsonObject,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {

 //  YOUR RESPONSE 
}
   }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();

        }
    });
   mRequestQueue.add(jsonObjReq);

// } }

Aurum answered 21/4, 2017 at 10:39 Comment(0)
P
0

try this :

new JsonArrayRequest(Method,Url,JsonArray,ResponseListener,ErrorListner) 

change to

new JsonObjectRequest(Method,Url,JsonArray,ResponseListener,ErrorListner)
Psycho answered 21/4, 2017 at 10:41 Comment(0)
V
0

Why don't you send params.put("Id",""+7); and then in your backend script you can typecast it to integersay for eg in php

$id_input = (int)mysqli_real_escape_string($conn,$_POST['Id'])

Vas answered 7/1, 2020 at 5:40 Comment(1)
Id show be an integer , We should not change backend code to fix a bug in android.Cissie

© 2022 - 2024 — McMap. All rights reserved.