我正在尝试向我在玻璃鱼服务器中部署的Web应用程序servlet发送请求,并使用volley HTTP库接收json响应。我设法从几个servlet获得响应,但是有一个servlet我收到错误 BasicNetwork.performRequest:意外的响应代码500 。我尝试使用切换HTTP方法,在servlet中将内容类型设置为“application / json”并实现getHeaders()
方法,并且可以针对此问题在SO中给出解决方案。但我还是无法解决这个问题。
我的排球请求如下:
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.i("RESPONSE",response.toString());
//Type type = new TypeToken<CartItem>() {}.getType();
//CartItem item = new Gson().fromJson(response.toString(), type);
//cartItem = item;
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.i("Volley_error", error.toString());
}
});
我在浏览器中的json响应如下所示:
{
"items": [{
"p_id": 1,
"p_name": "Multi Checked Shirt",
"p_price": 1234.0,
"p_size": "M",
"p_img": "uploads/products/Dorothy-Perkins-Multi-Checked-Shirt-4510-9254471-1-pdp_slider_l.jpg",
"p_qnty": 1
}, {
"p_id": 15,
"p_name": "Rust Solid Coloured Pant",
"p_price": 3500.0,
"p_size": "S",
"p_img": "uploads/products/Dorothy-Perkins-Rust-Solid-Coloured-Pant-971120977.jpg",
"p_qnty": 2
}],
"cart_total": 8234.0,
"total_items": 3
}
我的Servlet代码:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (request.getSession(false).getAttribute("cart") != null) {
ShoppingCart cart = (ShoppingCart) request.getSession(false).getAttribute("cart");
List<CartItem> cartItems = cart.getShoppingList();
List<Double> tot = new ArrayList<>();
CartModel model = new CartModel();
List<CartItemModel> cartItemModels = new ArrayList<>();
for (CartItem item : cartItems) {
CartItemModel itemModel = new CartItemModel(item.getProduct_id(),
cart.getNameofProduct(item.getProduct_id()),
cart.getPriceofProduct(item.getProduct_id(), item.getSize()),
item.getSize(),
path + cart.getImageofProduct(item.getProduct_id()),
item.getQnty());
cartItemModels.add(itemModel);
tot.add(cart.getPriceofProduct(item.getProduct_id(), item.getSize()) * item.getQnty());
}
model.setCart_total(cart.grandTotal(tot));
model.setTotal_items(cart.getTotalItemsOfTheCart());
model.setItems(cartItemModels);
Type type = new TypeToken<CartModel>() {
}.getType();
String element = new Gson().toJson(model, type);
response.getWriter().write(element);
}
}
我知道修改Volley库代码不是一个好主意,但我也尝试过。
if (statusCode < 200 || statusCode > 299) { throw new IOException();}
到
if (statusCode < 200 || statusCode > 505) {throw new IOException();}
然后我得到了错误:
JSONException: Value <!DOCTYPE of type java.lang cannot be converted to JSONObject
我是android新手。任何帮助都会很明显。谢谢。
更新:
以下是使用 HttpRequester 访问网址的方式:
答案 0 :(得分:3)
基于
JSONException:Value
<!DOCTYPE
您的servlet返回HTML,而不是纯文本JSON,因此无法解析。
由于您收到500内部服务器错误,因此HTML内容是真实错误。如果您从浏览器访问该URL,或使用Postman等工具,您将能够看到servlet的堆栈跟踪。
修复后,您可能需要在请求或响应中将Content-Type的标题设置为application / json以强制写入json。
有关解决方案的完整详情,请参阅How to send JSON back with Java