我尝试使用POST方法发送数据并获取JSONArray数组,但我没有从服务器获取数据,当我测试具有特定值的php文件时它就没问题了但是当我使用POST方法发送密钥然后不提供任何数据时。
这是我的JSONArray请求:
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, jsonURL, (String) null,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
int count = 0;
while (count < response.length()){
try {
JSONObject jsonObject = response.getJSONObject(count);
DataProvider dataProvider = new DataProvider(jsonObject.getString("Name"),
jsonObject.getString("Url"),
arrayList.add(dataProvider);
count++;
} catch (JSONException e) {
Toast.makeText(context,"Error",Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
CarFragment.adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}
){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> param = new HashMap<String,String>();
param.put("id","01675904620");
return param;
}
};
Singletone.getSingletone(context).addToRequest(jsonArrayRequest);
这是我的PHP代码:
<?php
$user_id = $_POST["id"];
$db_name = "andr";
$user_name = "user";
$password = "12345";
$server = "localhost";
$con = mysqli_connect($server,$user_name,$password,$db_name);
$result = mysqli_query($con, "SELECT * FROM user WHERE user_id = ".$user_id.";") or die("Error: " . mysqli_error($con));
$response = array();
while($row = mysqli_fetch_array($result))
{
array_push($response, array("Name"=>$row["name"],"Url"=>$row["image_url"]));
}
echo json_encode($response);
?>
答案 0 :(得分:1)
这是使用volley
向服务器发送数据的方法StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this,response,Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
}){
@Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("ID","1234");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
上面您可以看到,一旦您将ID发布到服务器,服务器就会将其响应发送到您的应用,并在String response
处可用。
您可以进一步处理此响应并获取您想要的任何内容。
JSONObject jsonObject=null;
try {
jsonObject = new JSONObject(json);//json is the response you get from server
users = jsonObject.getJSONArray(JSON_ARRAY);//JSON_ARRAY is the name of your array
ids = new String[users.length()];
for(int i=0;i<users.length();i++){
JSONObject jo = users.getJSONObject(i);
ids[i] = jo.getString("ID");
}
} catch (JSONException e) {
e.printStackTrace();
}
更多参考:
https://www.simplifiedcoding.net/android-volley-tutorial-to-get-json-from-server/ https://www.simplifiedcoding.net/android-volley-post-request-tutorial/
谢谢...... Happie Coding