Comme d'habitude, c'est un mémorandum ...
public class SampleDto implements Serializable {
private static final long serialVersionUID = 1L; //Il vaut mieux le générer correctement
private int id;
private String mail;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
}
protected String createJson4Sample(SampleDto dto) {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(dto);
} catch (JsonProcessingException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
log.error(sw.toString());
return null;
}
}
protected String requestJson(String method, String json, String urlPath, String charset,
String bearer) {
HttpURLConnection con = null;
if (StringUtils.isEmpty(charset)) {
charset = StringUtils.lowerCase(StandardCharsets.UTF_8.name());
}
String body = "";
try {
URL url = new URL(urlPath);
con = (HttpURLConnection)url.openConnection();
con.setRequestMethod(method);
con.setUseCaches(false);
con.setDoOutput(true);
con.setRequestProperty("Content-Type", "application/json; charset=" + charset);
if (StringUtils.isNotEmpty(bearer)) {
con.setRequestProperty("Authorization", "Bearer "+bearer);
}
OutputStreamWriter out = new OutputStreamWriter(new BufferedOutputStream(con.getOutputStream()));
out.write(json);
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = in.readLine();
while (line != null) {
body = body + line;
line = in.readLine();
}
}
catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
log.error(sw.toString());
return null;
}
finally {
if (con != null) {
con.disconnect();
}
}
return body;
}
protected boolean checkResponseJson(String response) {
ObjectMapper mapper = new ObjectMapper();
try {
if (StringUtils.isEmpty(response)) { return false; }
JsonNode root = mapper.readTree(response);
String success = root.get("success").asText();
String id = root.get("id").asText();
log.info("Response:" + id + ":" + success);
if (!"OK".equalsIgnoreCase(success)) {
return false;
}
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
log.error(sw.toString());
return false;
}
return true;
}
Je vous remercie pour votre travail acharné!
Recommended Posts