gpt4 book ai didi

java - 如何向Volley的JsonArrayRequest传递参数

转载 作者:太空宇宙 更新时间:2023-11-04 12:06:40 25 4
gpt4 key购买 nike

方法 getRequest 是对一般处理 GET 请求的尝试。

JsonArrayRequest 接受 JSONArray 对象,我可以使用此对象“JSONArray”来应用查询字符串参数还是我必须自己修改 URL。

public static void getRequest(final String tag, String url, JSONArray params, final GetRequest consumer, final ResponseFilter filt){
Log.d("Server",url);
String REQUEST_TAG = "GETMultiRequest";
JsonArrayRequest jsArrRequest = new JsonArrayRequest
(Request.Method.GET, url, params, new Response.Listener<JSONArray>() {

@Override
public void onResponse(JSONArray response) {
Log.d("Response", "received successfully");
consumer.update( filt.filter(response), tag );
}

}, new Response.ErrorListener(){
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
AppRequestSingleton.getInstance( ((Activity)consumer).getApplicationContext() ).addToRequestQueue(jsArrRequest, REQUEST_TAG);
}

最佳答案

可以使用StringRequest代替JsonArrayRequest并重写getParam(),也可以将参数从JSONArray更改为HashMap

代码应该是这样的:

public static void getRequest (final String tag, String url, final JSONArray params, final GetRequest consumer, final ResponseFilter filt) {

// Converting JSONArray parameters into HashMap
final HashMap<String, String> pairs = new HashMap<String, String> ();
for (int i = 0; i < params.length (); i++) {
JSONObject j = params.optJSONObject (i);
Iterator it = j.keys ();
while (it.hasNext ()) {
String n = (String) it.next ();
try {
pairs.put (n, j.getString (n));
} catch (JSONException e) {
e.printStackTrace ();
}
}
}

Log.d ("Server", url);
String REQUEST_TAG = "GETMultiRequest";
StringRequest strRequest = new StringRequest (Request.Method.GET, url,
new Response.Listener<String> () {
@Override
public void onResponse (String resp) {
try {
JSONArray response = new JSONArray (resp);
Log.d ("Response", "received successfully");
consumer.update (filt.filter (response), tag);
} catch (JSONException e) {
e.printStackTrace ();
}
}
},
new Response.ErrorListener () {
@Override
public void onErrorResponse (VolleyError error) {
VolleyLog.d (TAG, "Error: " + error.getMessage ());
}
}) {
@Override
protected Map<String, String> getParams () throws AuthFailureError {
return pairs;
}
};
AppRequestSingleton.getInstance (((Activity) consumer).getApplicationContext ()).addToRequestQueue (strRequest, REQUEST_TAG);
}

关于java - 如何向Volley的JsonArrayRequest传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40282434/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com