Volley,未在JsonArrayRequest中传递任何参数 [英] Volley, not passing any parameters in JsonArrayRequest
问题描述
我从将参数发布到服务器时出错,就像我的参数根本没有传递到服务器一样……我得到的只是:
I got an error from post parameters to my server, its like my params are not passing to my server at all...all I got is:
D/Searching: Error: org.json.JSONException: Value {"error_msg":"please choose city to view taxi list"}
该消息仅在isset($ _ POST ['from']等在我的服务器端中出现
that message only come out if isset($_POST['from'] so on in my serverside
这是我的代码:
// Creating volley request obj
JsonArrayRequest taxiReq = new JsonArrayRequest(Request.Method.POST, 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);
Taxi taxi = new Taxi();
taxi.settaxiname(obj.getString("taxiname"));
taxi.setThumbnailUrl(obj.getString("image"));
taxi.setdeparture(obj.getString("departure"));
taxi.setarrive(obj.getString("arrive"));
taxi.setseat(obj.getInt("seat"));
taxi.setcost(obj.getInt("cost"));
// adding taxi to taxi array
taxiList.add(taxi);
} 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) {
Log.d(TAG, "Error: " + error.getMessage());
}
})
{
@Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("from", textfrom_btn);
params.put("to", textto_btn);
params.put("seat", totalpassenger);
return params;
}
};
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(taxiReq);
这是json:
[
{
"image": "http://localhost/androidapp/taxiprofile/1.jpg",
"taxiname": "Taxi 1",
"from": "PTK",
"to": "SGU",
"departure": "08:00:00",
"arrive": "13:00:00",
"seat": 7,
"cost": 12
},
{
"image": "http://localhost/androidapp/taxiprofile/default.jpg",
"taxiname": "Taxi 2",
"from": "PTK",
"to": "SGU",
"departure": "08:00:00",
"arrive": "13:00:00",
"seat": 2,
"cost": 15
},
{
"image": "http://localhost/androidapp/taxiprofile/2.jpg",
"taxiname": "Taxi Untung Selalu",
"from": "PTK",
"to": "SGU",
"departure": "09:00:00",
"arrive": "14:00:00",
"seat": 3,
"cost": 13
}
]
这是我服务器中的php代码:
here my php code in my server:
<?php
include './include/DbHandler.php';
$db = new DbHandler();
// json response array
$response = array();
if (isset($_POST['from']) && isset($_POST['to']) && isset($_POST['totalpassenger'])) {
// receiving the post params
$from = $_POST['from'];
$to = $_POST['to'];
$totalpassenger = $_POST['totalpassenger'];
// get the user by email and password
$taxilist = $db->getTaxi($from, $to, $totalpassenger);
if ($taxilist != false) {
// taxi is found
foreach( $taxilist as $data ){
$response[] = array(
"image" => "http://".$_SERVER['SERVER_NAME'].dirname($_SERVER['REQUEST_URI']).$data["image"],
"taxiname" => $data["taxiname"],
"from" => $data["from"],
"to" => $data["to"],
"departure" => $data["departure"],
"arrive" => $data["arrive"],
"seat" => $data["seat"],
"cost" => $data["cost"]
);
}
echo json_encode($response);
} else {
$response["error_msg"] = "Sorry taxi is not listed";
echo json_encode($response);
}
} else {
$response["error_msg"] = "please choose city to view taxi list";
echo json_encode($response);
}
?>
代码中语法有误吗?
编辑 这是我使用CustomJsonRequest之后的日志猫
EDIT here is the logcat after I used CustomJsonRequest
03-29 16:11:06.070 25258-25258/com.testing W/EGL_genymotion: eglSurfaceAttrib not implemented
03-29 16:11:06.078 25258-25258/com.testing D/OpenGLRenderer: TextureCache::get: create texture(0xb85fe538): name, size, mSize = 389, 5184, 173360
03-29 16:11:06.082 25258-25258/com.testing D/OpenGLRenderer: TextureCache::get: create texture(0xb8489018): name, size, mSize = 391, 19264, 192624
03-29 16:11:55.714 25258-25258/com.testing D/Searching: []
推荐答案
前一天,我遇到了同样的问题.这不是您的代码的问题.实际上, JsonArrayRequest 类扩展了 JsonRequest ,后者扩展了 Request . 在 JsonRequest 类中, getBody()方法已被覆盖,看起来如此
Day's before I had Faced the same problem. it's not the problem with your code. Actually JsonArrayRequest class extends JsonRequest which extends Request. In JsonRequest class getBody() method has been overrided and it looks so
@Override
public byte[] getBody() {
try {
return mRequestBody == null ? null : mRequestBody.getBytes(PROTOCOL_CHARSET);
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
mRequestBody, PROTOCOL_CHARSET);
return null;
}
}
如果仔细观察,则不会调用getParams()
方法.
If you look closely getParams()
method is not called.
所以我要做的是创建一个new CLASS
,它像这样扩展Request<JsonArrayRequest>
So what I did was to create a new CLASS
which extends Request<JsonArrayRequest>
like this
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.util.Map;
public class CustomJsonRequest extends Request<JSONArray> {
private Listener<JSONArray> listener;
private Map<String, String> params;
public CustomJsonRequest(String url, Map<String, String> params,
Listener<JSONObject> reponseListener, ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.listener = reponseListener;
this.params = params;
}
public CustomJsonRequest(int method, String url, Map<String, String> params,
Listener<JSONArray> reponseListener, ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = reponseListener;
this.params = params;
}
@Override
protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
return params;
}
;
@Override
protected Response<JSONArray> 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));
}
}
@Override
protected void deliverResponse(JSONArray response) {
// TODO Auto-generated method stub
listener.onResponse(response);
}
}
您可以在此类中重写 getParams()方法,并按如下方式将其用于您的请求.
You can override the getParams() method in this class an use this for Your Request like this.
CustomJsonRequest request = new CustomJsonRequest(Request.Method.POST, url, params,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONArray response) {
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
我希望这会有所帮助.谢谢
I hope this is helpful. ThankYou
这篇关于Volley,未在JsonArrayRequest中传递任何参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!