Android Volley,如何动态传递发布参数 [英] Android volley, how to pass post parameters dynamically
问题描述
我是Google Volley网络库的新手(也是Android的新手!),并且我正在尝试以动态方式传递POST参数!
I'm new to google's Volley network library (and also to Android !), and I'm trying to pass POST arguments in a dynamic way !
目前,我正在覆盖:getParams()方法: 并以硬编码方式返回参数.
For now I am overiding the : getParams() method : And returning the params in an hard coded manner.
@Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("login", "my_login");
params.put("password", "my_password");
return params;
}
我想传递变量,而不是传递硬编码"字符串...
首先,我尝试将我的参数映射作为类的成员,但是在getParams()方法中无法使用类成员.
First I tried to put my Map of params as a member of my class, but class members are not avaible in the getParams() method.
也许我可以使用单例类来指定我要传递的参数,并使用其在getParams()方法中的实例将其取回?但是我认为这不是正确的方式.
Maybe I could use a singleton class to wich I could give the parameters I want to pass and get them back using its instance in the getParams() method ? But I don't think that it would be the right manner.
下面是我的Volley请求的漏洞代码:
Below is the hole code of my Volley's request :
RequestQueue queue = VolleySingleton.getInstance().getRequestQueue();
String url = "https://theUrlToRequest";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
@Override
public void onResponse(String response) {
JSONObject mainObject = null;
try {
Log.i("app", "Result = " + response);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) {
Log.i("app", "Fail on Login" + error.toString());
}
}
) {
@Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("login", "my_login");
params.put("password", "my_password");
return params;
}
};
queue.add(postRequest);
推荐答案
在这种情况下,您可以创建Class扩展StringRequest.添加一个attr来存储参数,并将其返回到getParams();
In that case , you can create a Class extends StringRequest. Add an attr to store params and return it in getParams();
MyStringRequest extends StringRequest{
private Map params = new HashMap();
public MyStringRequest (Map params,int mehotd,String url,Listener listenr,ErrorListener errorListenr){
super(mehotd,url,listenr,errorListenr)
this.params = params
}
@Override
protected Map<String, String> getParams(){
return params;
}
}
RequestQueue queue = VolleySingleton.getInstance().getRequestQueue();
String url = "https://theUrlToRequest";
Map<String, String> params = new HashMap<String, String>();
params.put("login", "my_login");
params.put("password", "my_password");
MyStringRequest postRequest = new MyStringRequest (params ,Request.Method.POST, url,
new Response.Listener<String>(){
},
new Response.ErrorListener(){
}
);
queue.add(postRequest);
这篇关于Android Volley,如何动态传递发布参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!