我在向Android JSON Array
发送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
等待回复,谢谢。
的Servlet
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);
...
的Android
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();
}
}
答案 0 :(得分:0)
在浏览器上,您正在尝试使用GET方法,而在您的代码中,您正在使用POST方法。尝试在代码中使用GET方法。以下是与HttpClient
GetMethod get = new GetMethod("http://www.example.com/page");
method.setQueryString(new NameValuePair[] {
new NameValuePair("q", "add"),
new NameValuePair("array", "[{"amount":"3","test":"test"}]"),
});
然后使用client.execute(post);
来呼叫服务器。
答案 1 :(得分:0)
StringEntity将您的[{}]编码为%5B%7B%7D%5D,servlet上的getParameter可能在您将其提供给JsonArray进行解析之前不对这些进行解码。所以url解码servlet上的参数可能是你正在寻找的修复。