Java Volley - 使用 JSONArrayRequest 发送 POST 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18048806/
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
Volley - Sending a POST request using JSONArrayRequest
提问by Marc Mailhot
I'm using Volley to interact with an API. I need to send a post request (with parameters) to a service that returns a JSON Array.
我正在使用 Volley 与 API 进行交互。我需要向返回 JSON 数组的服务发送一个 post 请求(带参数)。
JsonObjectRequest has a constructor that takes a method and a set of parameters
JsonObjectRequest 有一个构造函数,它接受一个方法和一组参数
JsonObjectRequest(int method, java.lang.String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener)
However JSONArrayRequest (the one I need) only has one constructor of the form
但是 JSONArrayRequest(我需要的那个)只有一个这样的构造函数
JsonArrayRequest(java.lang.String url, Response.Listener<JSONArray> listener, Response.ErrorListener errorListener)
How can I make this send a POST request with data?
我怎样才能让它发送一个带有数据的 POST 请求?
采纳答案by Itai Hanski
They're probably going to add it later, but in the meanwhile you can add the wanted constructor yourself:
他们可能会稍后添加它,但同时您可以自己添加想要的构造函数:
public JsonArrayRequest(int method, String url, JSONObject jsonRequest,
Listener<JSONArray> listener, ErrorListener errorListener) {
super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(),
listener, errorListener);
}
This isn't tested, though I see no reason this shouldn't work since the implementation details are in the super class: JsonRequest
.
这不是测试,但我认为没有理由这不应该工作,因为实施细则都在超类:JsonRequest
。
Try it and see if it works.
尝试一下,看看它是否有效。
EDIT:
编辑:
I called it! It took them almost two years after I answered this but the Volley team added this constructor on March 19, 2015 to the repo. Guess what? This is the EXACT syntax.
我叫它!在我回答这个问题后,他们花了将近两年的时间,但 Volley 团队于 2015 年 3 月 19 日将这个构造函数添加到回购中。你猜怎么着?这是 EXACT 语法。
回答by user98239820
May be your problem is solved but I hope this will be helpful for other users. What I did was, I created a new custom class by extending it.. here is the code.
可能您的问题已解决,但我希望这对其他用户有所帮助。我所做的是,我通过扩展它创建了一个新的自定义类......这是代码。
public class CustomJsonRequest extends Request {
Map<String, String> params;
private Response.Listener listener;
public CustomJsonRequest(int requestMethod, String url, Map<String, String> params,
Response.Listener responseListener, Response.ErrorListener errorListener) {
super(requestMethod, url, errorListener);
this.params = params;
this.listener = responseListener;
}
@Override
protected void deliverResponse(Object response) {
listener.onResponse(response);
}
@Override
public Map<String, String> getParams() throws AuthFailureError {
return params;
}
@Override
protected Response parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
}
you can use this class instead of JsonArrayRequest or JSonObjectRequest. And this also solve the problem of php not being able to catch post parameter in $_POST
您可以使用此类代替 JsonArrayRequest 或 JsonObjectRequest。这也解决了php在$_POST中无法捕获post参数的问题
回答by Jiang
just add some details about JsonArrayRequest. in \src\com\android\volley\toolbox,you can find out that default construct of JsonArrayRequest not support Method parameter, and volley add method(GET) in the construct, so if u want to use other method, try write it yourself
只需添加有关 JsonArrayRequest 的一些详细信息。在\src\com\android\volley\toolbox中,你可以发现JsonArrayRequest的默认构造不支持Method参数,并且在构造中volley添加了方法(GET),所以如果你想使用其他方法,请尝试自己编写
public class JsonArrayRequest 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 JsonArrayRequest(String url, Listener<JSONArray> listener, ErrorListener errorListener) {
super(Method.GET, url, null, listener, errorListener);
}
回答by Boy
I was lazy and did not build the Volley library myself (just used the .jar), hence have no source code...so in the anonymous new JSONArrayRequest
I added these functions:
我很懒惰,没有自己构建 Volley 库(只是使用了 .jar),因此没有源代码......所以在匿名 new 中JSONArrayRequest
我添加了这些函数:
// NO CONSTRUCTOR AVAILABLE FOR POST AND PARAMS FOR JSONARRAY!
// overridden the necessary functions for this
@Override
public byte[] getBody() {
try {
return paramsArray.toString().getBytes("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
@Override
public int getMethod() {
return Method.POST;
}
回答by Al1975
This code will make what you want
这段代码会让你想要什么
Volley.newRequestQueue(context).add(
new JsonRequest<JSONArray>(Request.Method.POST, "url/", null,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("param1", "one");
params.put("param2", "two");
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 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 Eltaf
The best and easy way to send parameter request and return custom response according to parameter using JSONarray Request is to add get paramater value in the URL itself.
使用 JSONarray 请求发送参数请求并根据参数返回自定义响应的最佳和简单方法是在 URL 本身中添加获取参数值。
String URL ="http://mentormentee.gear.host/android_api/Message.aspx?key="+keyvalue;
where keyvalue
parameter value and add this URL in the JsonArrayRequest URL simple.
wherekeyvalue
参数值并在 JsonArrayRequest URL 中简单地添加此 URL。
JsonArrayRequest searchMsg= new JsonArrayRequest(URL, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Message msg = new Message();
msg.setMessageThread(obj.getString("msgThread"));
msg.setUserName(obj.getString("Username"));
msg.setDate(obj.getString("msgDate"));
// adding movie to movies array
MessageList.add(msg);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
// hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(searchMsg);
}
回答by code_code
You can use this
package HelperClass;
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.util.Map;
/**
* A request for retrieving a {@link JSONArray} response body at a given URL.enter code here
*/
public class MyjsonPostRequest extends JsonRequest<JSONArray> {
protected static final String PROTOCOL_CHARSET = "utf-8";
/**
* Creates a new request.
* @param method the HTTP method to use
* @param url URL to fetch the JSON from
* @param requestBody A {@link String} to post with the request. Null is allowed and
* indicates no parameters will be posted along with request.
* @param listener Listener to receive the JSON response
* @param errorListener Error listener, or null to ignore errors.
*/
public MyjsonPostRequest(int method, String url, String requestBody,
Listener<JSONArray> listener, ErrorListener errorListener) {
super(method, url, requestBody, listener,
errorListener);
}
/**
* 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 MyjsonPostRequest(String url, Listener<JSONArray> listener, ErrorListener errorListener) {
super(Method.GET, url, null, listener, errorListener);
}
/**
* Creates a new request.
* @param method the HTTP method to use
* @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 MyjsonPostRequest(int method, String url, Listener<JSONArray> listener, ErrorListener errorListener) {
super(method, url, null, listener, errorListener);
}
/**
* Creates a new request.
* @param method the HTTP method to use
* @param url URL to fetch the JSON from
* @param jsonRequest A {@link JSONArray} to post with the request. Null is allowed and
* indicates no parameters will be posted along with request.
* @param listener Listener to receive the JSON response
* @param errorListener Error listener, or null to ignore errors.
*/
public MyjsonPostRequest(int method, String url, JSONArray jsonRequest,
Listener<JSONArray> listener, ErrorListener errorListener) {
super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
errorListener);
}
/**
* Creates a new request.
* @param method the HTTP method to use
* @param url URL to fetch the JSON from
* @param jsonRequest A {@link JSONObject} to post with the request. Null is allowed and
* indicates no parameters will be posted along with request.
* @param listener Listener to receive the JSON response
* @param errorListener Error listener, or null to ignore errors.
*/
public MyjsonPostRequest(int method, String url, JSONObject jsonRequest,
Listener<JSONArray> listener, ErrorListener errorListener) {
super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
errorListener);
}
/**
* Constructor which defaults to <code>GET</code> if <code>jsonRequest</code> is
* <code>null</code>, <code>POST</code> otherwise.
*
* @see #MyjsonPostRequest(int, String, JSONArray, Listener, ErrorListener)
*/
public MyjsonPostRequest(String url, JSONArray jsonRequest, Listener<JSONArray> listener,
ErrorListener errorListener) {
this(jsonRequest == null ? Method.GET : Method.POST, url, jsonRequest,
listener, errorListener);
}
/**
* Constructor which defaults to <code>GET</code> if <code>jsonRequest</code> is
* <code>null</code>, <code>POST</code> otherwise.
*
* @see #MyjsonPostRequest(int, String, JSONObject, Listener, ErrorListener)
*/
public MyjsonPostRequest(String url, JSONObject jsonRequest, Listener<JSONArray> listener,
ErrorListener errorListener) {
this(jsonRequest == null ? Method.GET : Method.POST, url, jsonRequest,
listener, errorListener);
}
@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 Andriya
JsonArrayRequest req = new JsonArrayRequest(urlJsonArry,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
// Parsing json array response
// loop through each json object
jsonResponse = "";
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
String name = person.getString("name");
String email = person.getString("email");
JSONObject phone = person
.getJSONObject("phone");
String home = phone.getString("home");
String mobile = phone.getString("mobile");
jsonResponse += "Name: " + name + "\n\n";
jsonResponse += "Email: " + email + "\n\n";
jsonResponse += "Home: " + home + "\n\n";
jsonResponse += "Mobile: " + mobile + "\n\n\n";
}
txtResponse.setText(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
}