Since it is not necessary to save the data that I want to have temporarily in the DB, I made it possible to post and share it as a JSON String.
postJSON
public String postJson(String json, String path) {
HttpURLConnection uc;
try {
URL url = new URL("http://host"+path);
uc = (HttpURLConnection) url.openConnection();
uc.setRequestMethod("POST");
uc.setUseCaches(false);
uc.setDoOutput(true);
uc.setRequestProperty("Content-Type", "application/json; charset=utf-8");
OutputStreamWriter out = new OutputStreamWriter(
new BufferedOutputStream(uc.getOutputStream()));
out.write(json);
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
String line = in.readLine();
String body = "";
while (line != null) {
body = body + line;
line = in.readLine();
}
uc.disconnect();
return body;
} catch (IOException e) {
e.printStackTrace();
return "client - IOException : " + e.getMessage();
}
}
Receives POSTed data and stores it as JSONArray and JSONObject.
doPost
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
BufferedReader br = new BufferedReader(request.getReader());
String line = br.readLine();
String body = "";
if (line != null) {
body = body + line;
line = br.readLine();
}
PrintWriter out = response.getWriter();
out.println("{\"status\":\"OK\"}");
out.flush();
out.close();
try {
LinkedList todo = new LinkedList();
JSONArray ja = new JSONArray(body);
for (int i = 0; i < ja.length(); i++) {
JSONObject tdj = (JSONObject) ja.get(i);
//Processing addition
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Recommended Posts