网址示例= http://webapi.example.com/api/order?data= {... list [{...},{...}]}
GsonRequest request = new GsonRequest<OrderResponse>("URL example", null,
OrderResponse.class, null, new Response.Listener<OrderResponse>() {
@Override
public void onResponse(OrderResponse response) {
if (response.isSuccess()) {
//sendNotification();
} else {
Toast.makeText(DeliveryManagementActivity.this, "Error in Server", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: " + error.getMessage());
}
});
对于上面的代码,我收到400错误。
GsonRequest request = new GsonRequest<OrderResponse>(UrlConstants.SEND_ORDERS_URL, getParams(),
OrderResponse.class, header, new Response.Listener<OrderResponse>() {
@Override
public void onResponse(OrderResponse response) {
if (response.isSuccess()) {
sendNotification();
} else {
Toast.makeText(DeliveryManagementActivity.this, "Error in Server", Toast.LENGTH_SHORT).show();
}
hideLoader();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
VolleyLog.e("Error: " + error.getMessage());
Toast.makeText(DeliveryManagementActivity.this, "Error " + error.getMessage(), Toast.LENGTH_SHORT).show();
hideLoader();
}
});
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
return headers;
}
private Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("orderData", requestData.getOrderRequest(requestData));
return params;
}
对于上述情况,我总是从服务器得到错误的错误响应。我从第一个请求方法复制了请求,并使用浏览器URL来访问API。它运作良好。
编辑:
更改为第二种方式后,请求如下所示。
网址 = www.url.com/addOrder.php?
params = {“orderData”:“{\”deliveryTime \“:\”2017-12-10 01:13:00 \“,\”orderDetail \“:[{\” courseId \ “:\” 1 \” \ “foodQuantity \”:\ “2 \” \ “offer_id \”:\ “ - 1 \” \ “类型\”:\ “1 \”}],\ “用户ID \”:\ “7 \”,\ “用户位置\”:\ “17 \”}“}
orderData 也在json中解析并缺少 = 。这是问题所在。问题顶部的网址是实际的,并且正在运行。
答案 0 :(得分:0)
查询参数名称 orderData ? url中使用的查询参数是 data 。 其他代码看起来还不错。
答案 1 :(得分:0)
对网址进行编码后,问题就解决了。
try {
param = URLEncoder.encode("json", "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String url = baseUrl + params;
GsonRequest request = new GsonRequest<OrderResponse>(url, null,
OrderResponse.class, null, new Response.Listener<OrderResponse>() {
@Override
public void onResponse(OrderResponse response) {
if (response.isSuccess()) {
//sendNotification();
} else {
Toast.makeText(DeliveryManagementActivity.this, "Error in Server", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: " + error.getMessage());
}
});