Android Volley POST Json到服务器 [英] Android Volley POST Json to Server
本文介绍了Android Volley POST Json到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Volley在Android设备和Web服务器之间传输数据.
我发现了有关将数据列表发送到服务器的问题.
例如,我的班级将生成如下数据集:
{
"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"
}
}
如何将这些数据发送到服务器?
我找到了一些将数据发布到服务器的教程.它必须使用hashmap. 有更好的解决方案来处理这种情况吗?
解决方案
- 发出像下面这样的排球请求,采用类似
POST/GET
的方法,url
,response & error
侦听器.并且用于发送您的json覆盖getBody()
方法,在其中传递您要发送的json. - 制作
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 am using Volley to transfer the data between Android device and web server.
I found a issue about sending a list of data to the server.
For example, my class will generate the data set like this:
{
"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"
}
}
How can i send those data to Server?
I found some tutorial of Post data to server. It must using hashmap. Any better solution to handle this case?
解决方案
- Make a volley request like bellow which takes method like
POST/GET
,url
,response & error
listener. And For sending your json overridegetBody()
method in which pass the json you want to send. - Make a
RequestQueue
& add the request to it. You might start it by callingstart()
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
这篇关于Android Volley POST Json到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文