简体   繁体   English

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

[英]Send data to server as json format using android Volley

I want to send data from android app to remote server in JSON format. 我想以JSON格式将数据从android应用发送到远程服务器。 Below is my json format :- 以下是我的json格式:-

{
  "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? 谁能告诉我如何使用Volley发送此数据?

  1. Make a volley request like bellow which takes method like POST/GET , url , response & error listener. 发出以下请求,例如波纹管,采用POST/GETurlresponse & error侦听器之类的方法。 And For sending your json override getBody() method in which pass the json you want to send. 对于发送json,请重写getBody()方法,并在其中传递要发送的json。
  2. Make a RequestQueue & add the request to it. 创建一个RequestQueue并将请求添加到其中。 You might start it by calling start() 您可以通过调用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 为了发送JSON类型的数据,您应该使用齐射发出JSON请求

// 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. 其中object是您要发送的JSONObject Ask if you want more clarification. 询问是否要进一步澄清。

Mark this up if this helps you. 如果可以,请对此进行标记。

1. Add Volley and Gson Dependency into build.gradle: 1.将Volley和Gson Dependency添加到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. 注意:如果String变量中包含JSON数据,则只需将String变量作为第三个参数传递给JsonObjectRequest。 (Go to Step 6) (转到步骤6)

If you have JSON data in your classes then just pass the class in gson.toJson() of the third parameter of JsonObjectRequest. 如果您的类中包含JSON数据,则只需在JsonObjectRequest的第三个参数的gson.toJson()中传递该类即可。 (Go to Step 6) (转到步骤6)

If you want to get the data in class then you need to create classes structure same as JSON data. 如果要在类中获取数据,则需要创建与JSON数据相同的类结构。 (Go to step 2) (转到步骤2)

2. Then create the POJO classes for the above JSON Structure using http://www.jsonschema2pojo.org/ 2.然后使用http://www.jsonschema2pojo.org/为上述JSON结构创建POJO类

Example Shown in image: Red marks showing the changes needed to make on site 图片中的示例: 红色标记显示需要在现场进行的更改

Then you will get two classes as ContactsTop and Contact. 然后您将获得两个类,分别为ContactsTop和Contact。 Note: ContactsTop is name provided at the time of creating POJO classes from jsonschema2pojo.com 注意:ContactsTop是从jsonschema2pojo.com创建POJO类时提供的名称。

3. Add above generated classes into your project 3.将上面生成的类添加到您的项目中

4. Create Volley RequestQueue object and gson object. 4.创建Volley RequestQueue对象和gson对象。

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

5. Then add above JSON data to POJO Classes. 5.然后将上述JSON数据添加到POJO类。

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. 6.创建JSONObject以使用您的数据调用Web服务。

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. 7.将您的jsonObjectRequest添加到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). (不要忘记添加此行。这将在RequestQueue中添加您的请求,然后只有您将从服务中获得JSON响应或错误)。 Don't forget to add INTERNET Permission in AndroidManifest.xml 不要忘记在AndroidManifest.xml中添加INTERNET权限

 requestQueue.add(jsonObjectRequest);

Then you will get Response or Error from your Remote Service in android Log monitor. 然后,您将从android Log Monitor中的“远程服务”获得响应或错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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