I have a simple app communicating with its Servlet backend through an Async task. I have some trouble understanding how the messages are wrapped up and how to manipulate th
Set the servlet's content type to application/json
and return a JSON string (e.g using Gson or Jackson to serialize the result.
On the Android side you can deserialize the JSON string, either using Android's built-in JSON classes or (better) using the same libraries you used in your servlet.
For example, if Tour
is something like:
public class Tour {
// some simple int/string/list fields
}
You can build a response class like:
public class Tours {
private List<Tour> tours;
// ...
}
Then on the server side (see this question, I'm using Gson here):
List<Tour> listOfTours = ...;
Tours tours = new Tours(listOfTours);
response.setContentType("application/json");
PrintWriter out = response.getWriter();
out.print((new Gson()).toJson(tours));
out.flush();
And on the client side:
String jsonResponse = ...;
Tours tours = (new Gson()).fromJson(jsonResponse, Tours.class);
There are some optimizations to be made, but that could get you started.
Also, consider using OkHttp for your HTTP connections instead of using HttpClient
, you'll probably end up with simpler and more robust code.