使用Android Volley将数据以json格式发送到服务器 [英] Send data to server as json format using android Volley
本文介绍了使用Android Volley将数据以json格式发送到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想以JSON格式将数据从android应用发送到远程服务器. 以下是我的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"
}
]
}
任何人都可以告诉我如何使用Volley发送此数据吗?
解决方案
- 发出像下面这样的排球请求,采用类似
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 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?
解决方案
- 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将数据以json格式发送到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文