I have a problem sending JSON Array to Servlet from Android. But I am able to send the same JSON Array via the Browser. I have spent many hours trying to solve this problem, but can’t find a solution.
URL = "http://192.168.*.*:8080/Test/TestServlet?q=add&array="
And I have add JSON Array at the end:
[{"amount":"3","test":"test",...}]
GlassFish server error:
org.json.JSONException: A JSONArray text must start with '[' at character 0 of
Waiting for reply, thank you.
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();
}
}
On browser you are trying with GET method whereas in your code you are using POST method. Try using the GET method in your code. Following is a example of GET method to be used with
HttpClientthen use
client.execute(post);to call the server.