我从post参数到我的服务器出错了,就像我的params根本没有传递给我的服务器......我得到的只是:
D/Searching: Error: org.json.JSONException: Value {"error_msg":"please choose city to view taxi list"}
该消息仅在isset时出现($ _ POST ['from']在我的服务器端
这是我的代码:
// 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代码:
<?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后的logcat
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: []
答案 0 :(得分:1)
在我遇到同样问题之前的一天。这不是您的代码的问题。实际上 JsonArrayRequest 类扩展了 JsonRequest ,扩展了请求。 在 JsonRequest 类 getBody()方法已被覆盖,看起来如此
@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()
方法不会被调用。
所以我所做的就是创建一个new CLASS
,其扩展Request<JsonArrayRequest>
就像这样
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()方法,并将此用作您的请求。
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) {
}
});
我希望这会有所帮助。 THANKYOU
答案 1 :(得分:0)
我上周遇到了这个问题,这与Volley没有以正确的方式设置POST参数有关。而不是修复它我只是采用GET请求,看起来你可以做同样的事情,因为参数似乎不是那么敏感。
如果您想尝试GET请求,可以这样做。当然你也必须在PHP中从POST切换到GET!
网址的创建方式如下:
URL url = null;
String query = "?from=" + textfrom_btn +
"&to=" + textto_btn +
"&seat=" + totalpassenger;
try {
url = new URL("http", "www.Foo.com", "Bar.php" + query);
}catch (MalformedURLException ex){
ex.printStackTrace();
}
请求如下所示:
JsonArrayRequest taxiReq = new JsonArrayRequest(Request.Method.GET, url.toString(), null, new Response.Listener<JSONArray>(){
@Override
public void onResponse(JSONArray response){
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();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener(){
@Override
public void onErrorResponse(VolleyError error){
error.printStackTrace();
}
});
MyApplication.getInstance().addToRequestQueue(taxiReq);
}