I've searched and tested for 2 days every code I have found, with absolutely no luck. I'm sending a json file to a servlet, and I'm pretty sure that data are correctly sent; for some reason I cannot get them from the input stream of the request.
Here the code from the data sender:
{
...
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
Gson gson = new Gson();
String jsonString = gson.toJson(<POJO_to_send>).toString();
wr.writeBytes(URLEncoder.encode(jsonString,"UTF-8"));
wr.flush();
wr.close();
String responseMessage = con.getResponseMessage();
...
}
The code from the servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String s = "";
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
while((s=br.readLine())!=null) {
s = br.readLine();
sb.append(s);
}
String jsonString = sb.toString();
if (jsonString != null) {
jsonString = br.readLine();
}else{
IOException ioex = new IOException("Error reading data.");
throw(ioex);
}
}
For some reason that I have not found yet, sb.toString() result in null value, because the sb is an empty string. From debug I've found that the buf value of input stream of the request seems not empty (at least there are some byte data in it, and seems to me that they are the same of the data output writer of the sender).
Did you see some error that I have missed? Can I check data send before they reach the servlet (maybe the encoding fails somewhere)?
Any advise/idea?
Thank you