且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Android Volley将数据以json格式发送到服务器

更新时间:2023-01-01 17:13:20

  1. 发出像下面这样的排球请求,采用类似POST/GET的方法, urlresponse & error侦听器.并且用于发送您的json覆盖 getBody()方法,在其中传递您要发送的json.
  2. 制作RequestQueue&向其中添加请求.您可以通过以下方式开始 呼叫start()

尝试一下:

// 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();

有关更多信息,请参见 >

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