我在从 Android发送JSON Array
到t 时遇到问题。Servle
但我可以JSON Array
通过浏览器发送相同的内容。我花了很多时间试图解决这个问题,但找不到解决方案。
URL = "http://192.168.*.*:8080/Test/TestServlet?q=add&array="
我在最后添加了 JSON 数组:
[{"amount":"3","test":"test",...}]
GlassFish服务器错误:
org.json.JSONException: A JSONArray text must start with '[' at character 0 of
等待回复,谢谢。
小服务程序:
protected void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/json");
PrintWriter out = response.getWriter();
String req = request.getParameter("q");
try
{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver found");
dbConnect = DriverManager.getConnection("jdbc:mysql://localhost/***",
"root", "***");
dbStatement = dbConnect.createStatement();
if (req.equals("add")) {
String json_array = request.getParameter("array");
String query = null;
org.json.JSONArray jArray = new org.json.JSONArray(json_array);
for (int i = 0; i < jArray.length(); i++)
{
org.json.JSONObject obj = jArray.getJSONObject(i);
query =
"INSERT INTO *** (...) VALUES(" + obj.getInt("***") + ",'" +
obj.getString("***") + "','" + obj.getString("***") + "','" +
obj.getString("***") + "'," + obj.getDouble("***") + "," +
obj.getDouble("***") + "," + obj.getDouble("***") + ",'" +
obj.getString("***") + "','"+obj.getString("***")+"','','"+
obj.getString("***") + "')";
}
dbStatement.executeUpdate(query);
...
安卓
protected void sendJson(JSONArray json)
{
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpResponse response;
try
{
HttpPost post = new HttpPost(URL);
StringEntity se = new StringEntity(json.toString());
Log.i("JSON before sending", json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
/*Checking response */
if(response!=null)
{
InputStream in = response.getEntity().getContent();
//Get the data in the entity
}
}
catch(Exception e)
{
e.printStackTrace();
}
}