![](/img/trans.png)
[英]Send array from android and receive at PhP server using Volley
[英]How to send java string array to php? using volley (Android)
我试图将以下数据发送到我的php,但是如果我放置多个s1变量,程序将崩溃。
Java代码:
//my java code goes here
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("s1",max[0]);
params.put("s1",max[1]);
params.put("s1",max[3]);
return params;
}
PHP代码:
//my php code goes here
<?php
$con = mysqli_connect('localhost','myuser','mypass');
mysqli_select_db($con,'mydb');
$checked = $_POST["s1"];
$SQL = "INSERT INTO TABLE VALUES ('$checked[0]','$checked[1]','$checked[2]')";
mysqli_query($con,$SQL);
?>
地图只能存储一个键和一个值,不允许重复的键,因此简而言之,您只是发送一个值,并尝试使用索引(不存在)来获取多个值,因此例外
解决方案:要么使用不同的键,然后使用服务器上的那些键获取值,要么发送整个数组
要发送整个数组,只需创建JSONObject
或JSONArray
请求而不是String
有我的例子:
public void todo(String value, String value2)
{
StringRequest stringRequest = new StringRequest(Request.Method.POST, "https://adress.com/script.php", new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//response
Log.d("Response", response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}
){
@Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("s1", value1);
params.put("s2", value2);
return params;
}
};
MySingleton.getInstance(this).addToRequestque(stringRequest);
}
MySingleton.java:
public class MySingleton {
private static MySingleton mInstance;
private RequestQueue requestQueue;
private static Context mCtx;
private MySingleton(Context context)
{
mCtx = context;
requestQueue = getRequestQueue();
}
public RequestQueue getRequestQueue()
{
if(requestQueue==null)
{
requestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return requestQueue;
}
public static synchronized MySingleton getInstance(Context context)
{
if (mInstance==null)
{
mInstance = new MySingleton(context);
}
return mInstance;
}
public <T>void addToRequestque(Request<T> request)
{
requestQueue.add(request);
}
}
我假设这正在生成查询字符串,例如
?s1=A&s1=B&s1=C
这将导致s1的每个值覆盖最后一个值,并且s1将包含“ C”,而不是数组。
如果希望s1为数组,则需要使用s1 []作为标签,因此它将生成一个查询字符串,例如
?s1[]=A&s1[]=B&s1[]=C
因此,您的Java将是:
params.put("s1[]",max[0]);
params.put("s1[]",max[1]);
params.put("s1[]",max[3]);
但是,这确实很重要,如果您的PHP页面以任何方式向公众开放,则在您将发布的值开放给SQL注入攻击之前,您不要转义它们(即使不是,您仍然应该警惕)反对)看看http://php.net/manual/en/mysqli.real-escape-string.php
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.