Java 使用 android volley 库发送 JSONArray POST 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28656865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Send a JSONArray POST request with android volley library
提问by
I would like to send and receive a Json Array with volley. Now I can receive an array and it's ok but I don't know how to send a request (For example: with post method).
我想用凌空发送和接收一个 Json 数组。现在我可以接收一个数组并且可以,但是我不知道如何发送请求(例如:使用 post 方法)。
JsonArrayRequest arrayReq = new JsonArrayRequest(URL,
new Listener<JSONArray>() {
}
回答by Y.S
Here is an example:
下面是一个例子:
// Define the web service URL
final String URL = "http://www.someurl.com";
// POST params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("name", "raha tamjid");
// Define the POST request
JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
// Add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(req);
How the POST request differs is that it takes a JSONObject
as parameter.
POST 请求的不同之处在于它采用 aJSONObject
作为参数。
EDIT 1:
编辑 1:
If you have Volley
installed as a library project in your IDE, then just define a new constructor
如果您已Volley
在 IDE 中作为库项目安装,则只需定义一个新的构造函数
public JsonArrayRequest(int method, String url, JSONObject jsonRequest,
Listener<JSONArray> listener, ErrorListener errorListener) {
super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener, errorListener);
}
inside the class JsonArrayRequest
which is present in the Volley
library code. Now you can use this to create JsonArrayRequest
objects and add them to the RequestQueue
.
在库代码中JsonArrayRequest
存在的类中Volley
。现在您可以使用它来创建JsonArrayRequest
对象并将它们添加到RequestQueue
.
EDIT 2:
编辑2:
1.Get the Volley library project from here. Download the project and set it up in your IDE.
1.从这里获取 Volley 库项目。下载项目并在您的 IDE 中进行设置。
2.Make the modification to the JsonRequest
class (found in com.android.volley.toolbox
namespace) as discussed in EDIT 1.
2.对JsonRequest
类(在com.android.volley.toolbox
命名空间中找到)进行修改,如EDIT 1 中所述。
3.Delete the volley.jar
from the libs
folder of your APPLICATION PROJECT.
3.volley.jar
从libs
您的APPLICATION PROJECT文件夹中删除。
4.Now go to Project Properties -> Android -> Library and click on Add. From here select the Volley
project. Clean & Rebuild.
4.现在转到 Project Properties -> Android -> Library 并单击Add。从这里选择Volley
项目。清洁和重建。
5.Now in your APPLICATION PROJECTyou can make a POST JsonArrayRequest
just like how we make a POST JsonObjectRequest
and get a JSONArray
in the Response
.
5.现在在您的应用程序项目中,您可以JsonArrayRequest
像我们制作 POSTJsonObjectRequest
并JSONArray
在Response
.
回答by vrbsm
List<Map<String,String>> listMap = new ArrayList<Map<String, String>>();
Map<String,String> map = new HashMap<String,String>();
try {
map.put("email", customer.getEmail());
map.put("password",customer.getPassword());
} catch (Exception e) {
e.printStackTrace();
}
listMap.add(map);
String url = PersonalConstants.BASE_URL+"/url";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.POST, url, String.valueOf(new JSONArray(listMap)),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonObject) {
Log.d(App.TAG, jsonObject.toString());
}
}, new Response.ErrorListener (){
@Override
public void onErrorResponse(VolleyError volleyError) {
Log.d(App.TAG,volleyError.toString());
}
}
);
App.getInstance().getmRequestQueue().add(jsonObjectRequest);
回答by Andriya
Create a class and extend JsonArrayRequest then override
创建一个类并扩展 JsonArrayRequest 然后覆盖
@Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("name", "value");
return params;
}
and add a new constructor and in it call
super(Method.POST, url, null, listener, errorListener);
or use this class
public class PostJsonArrayRequest extends JsonRequest<JSONArray> {
/**
* Creates a new request.
* @param url URL to fetch the JSON from
* @param listener Listener to receive the JSON response
* @param errorListener Error listener, or null to ignore errors.
*/
public PostJsonArrayRequest(String url, Response.Listener<JSONArray> listener, Response.ErrorListener errorListener) {
super(Method.POST, url, null, listener, errorListener);
}
@Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("name", "value");
return params;
}
@Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString =
new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONArray(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
}
回答by Vinay Jaju
Create a new java class named JsonArrayPostRequest now you can use it like the previous request, just replace JSONArrayRequest with JsonArrayPostRequest and pass the correct parameters
创建一个名为 JsonArrayPostRequest 的新 java 类,现在您可以像之前的请求一样使用它,只需将 JSONArrayRequest 替换为 JsonArrayPostRequest 并传递正确的参数
public class JsonArrayPostRequest extends Request<JSONArray>{
private Map<String,String> mParam;
private Listener<JSONArray> mListener;
public JsonArrayPostRequest(String url,Listener<JSONArray> listener, ErrorListener errorListener,Map param) {
super(Request.Method.POST, url, errorListener);
mListener=listener;
mParam=param;
}
@Override
protected Map<String, String> getParams() throws AuthFailureError {
return mParam;
}
@Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString =
new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONArray(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
@Override
protected void deliverResponse(JSONArray response) {
mListener.onResponse(response);
}
}
USE:
用:
JsonArrayPostRequest request = new JsonArrayPostRequest(URL,new Response.Listener<JSONArray>(),
new Response.ErrorListener() ,params);