Comme il n'est pas nécessaire de sauvegarder les données que je souhaite avoir temporairement dans la base de données, j'ai rendu possible de les publier et de les partager avec une chaîne JSON.
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();
}
}
Reçoit les données POSTées et les stocke en tant que JSONArray et 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);
//Ajout de traitement
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Recommended Posts