2016-04-06 224 views
0

我使用Volley在Android设备和Web服务器之间传输数据。Android Volley POST Json到服务器

我发现有关将数据列表发送到服务器的问题。

例如,我的课将生成的数据集是这样的:

{ 
    "1": { 
    "1_aID": "5", 
    "2_aID": "5", 
    "3_aID": "5", 
    "4_aID": "5" 
    }, 
    "2": { 
    "1_bID": "3", 
    "2_bID": "3", 
    "3_bID": "3" 
    }, 
    "3": { 
    "1_cID": "4" 
    } 
} 

我怎样才能将这些数据发送到服务器?

我发现一些Post数据到服务器的教程。它必须使用hashmap。 任何更好的解决方案来处理这种情况?

+1

那么在我的情况下,我已经数组转换为字符串,然后发送数据到服务器我有这样的数据是我的应用程序[{“color”:“yellow”},{“color”:“green”}] –

+0

您面临的问题是什么? –

+0

你是JsonRequest类吗? – Jois

回答

1
  1. 使像波纹管齐射请求这需要像方法POST/GETurlresponse & 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(); 

欲了解更多信息请参阅this

+0

如果您使用的是PHP,请不要忘记这个JSON将存储在'php:// input'中,而不是'$ _REQUEST'中。获取它像'$ obj = json_decode(file_get_contents(“php:// input”));' –

1

尝试此

JSONObject rootObj = new JSONObject(); 
JSONObject oneObject = new JSONObject(); 
oneObject.put("1_aID","5"); 
... 
... 
JSONObject threeObject = new JSONObject(); 
oneObject.put("1_cID","4"); 
rootObj("1",oneObject); 
... 
... 
rootObj("3",threeObject); 

new JsonObjectRequest(Request.Method.POST, 
       url, 
       rootObj.toString(), 
responselistner, 
errorlistner); 
相关问题