简体   繁体   中英

Send data to server as json format using android Volley

I want to send data from android app to remote server in JSON format. Below is my json format :-

{
  "contacts": [
    {
      "name": "ritva",
      "phone_no": "12345657890",
      "user_id": "1"
    },
    {
      "name": "jisa",
      "phone_no": "12345657890",
      "user_id": "1"
    },
    {
      "name": "tithi",
      "phone_no": "12345657890",
      "user_id": "1"
    }
  ]
}

Can any one tell me how do I send this data using Volley?

  1. Make a volley request like bellow which takes method like POST/GET , url , response & error listener. And For sending your json override getBody() method in which pass the json you want to send.
  2. Make a RequestQueue & add the request to it. You might start it by calling start()

Try this :

// Instantiate the RequestQueue.
    RequestQueue queue = Volley.newRequestQueue(this);
    String url ="http://www.google.com";

    // Request a string response from the provided URL.
    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    // your response

                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            // error
        }
    }){
        @Override
        public byte[] getBody() throws AuthFailureError {
            String your_string_json = ; // put your json
            return your_string_json.getBytes();
        }
    };
    // Add the request to the RequestQueue.
    queue.add(stringRequest);
    requestQueue.start();

For more info see this

For sending JSON type data you should make a JSON request using volley

// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";

     JsonObjectRequest jsObjRequest = new JsonObjectRequest
            (Request.Method.POST, url, obj, new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {


                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    // TODO Auto-generated method stub

                }
            });
// Add the request to the RequestQueue.
queue.add(stringRequest);
requestQueue.start();

Where object is your JSONObject that you want to send. Ask if you want more clarification.

Mark this up if this helps you.

1. Add Volley and Gson Dependency into build.gradle:

'com.mcxiaoke.volley:library:1.0.19' 
'com.google.code.gson:gson:2.7'

Note: If you have JSON data in String variable then just pass the String variable as third parameter in JsonObjectRequest. (Go to Step 6)

If you have JSON data in your classes then just pass the class in gson.toJson() of the third parameter of JsonObjectRequest. (Go to Step 6)

If you want to get the data in class then you need to create classes structure same as JSON data. (Go to step 2)

2. Then create the POJO classes for the above JSON Structure using http://www.jsonschema2pojo.org/

Example Shown in image: Red marks showing the changes needed to make on site

Then you will get two classes as ContactsTop and Contact. Note: ContactsTop is name provided at the time of creating POJO classes from jsonschema2pojo.com

3. Add above generated classes into your project

4. Create Volley RequestQueue object and gson object.

RequestQueue requestQueue = Volley.newRequestQueue(this);
Gson gson = new Gson();

5. Then add above JSON data to POJO Classes.

ContactsTop contactsTop=new ContactsTop();
List<Contact> contactList =new ArrayList();
Contact contact=new Contact();

contact.setPhoneNo("12345657890");
contact.setName("ritva");
contact.setUserId("1");

contactList.add(contact);
contactsTop.setContacts(contactList);

6. Create JSONObject to call web service with your data.

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, "www.your-web-service-url.com/sendContact.php", gson.toJson(contactsTop), new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
             Log.v("Volley:Response ", ""+response.toString());
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.v("Volley:ERROR ", error.getMessage().toString());
        }
    });

7. Add your jsonObjectRequest into requestQueue. (Don't forget to add this line. this is will add your request in RequestQueue and then only you will get JSON Response or Error from your Service). Don't forget to add INTERNET Permission in AndroidManifest.xml

 requestQueue.add(jsonObjectRequest);

Then you will get Response or Error from your Remote Service in android Log monitor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM