我知道使用JsonArrayRequest的POST请求不能与Volley一起开箱即用,但我看到这篇帖子here谈到了添加构造函数来处理这个问题。他们的实施是这样的:
public JsonArrayRequest(int method, String url, JSONObject jsonRequest,
Listener<JSONArray> listener, ErrorListener errorListener) {
super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(),
listener, errorListener);
}
我如何将其添加为构造函数?上述问题提到将其放入Volley工具库中。我将Volley导入为.jar,因此我不确定如何添加这样的构造函数,或者这是否是最好的方法。非常感谢任何帮助。
修改
我已根据建议使用override和constructor创建了以下类。这是班级:
public class PostJsonArrayRequest extends JsonArrayRequest {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("name", "value");
return params;
}
public PostJsonArrayRequest(int method, String url, JSONObject jsonRequest,
Listener<JSONArray> listener, ErrorListener errorListener) {
super(Method.POST, url, null, listener, errorListener);
}
}
在线路上打电话给我The constructor JsonArrayRequest(int, String, null, Response.Listener<JSONArray>, Response.ErrorListener) is undefined
我该如何纠正?
答案 0 :(得分:2)
创建一个类并扩展JsonArrayRequest
然后覆盖
@Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("name", "value");
return params;
}
并添加一个新的构造函数并在其中调用
super(Method.POST, url, null, listener, errorListener);
或使用此课程
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));
}
}
}