代码如下,希望如果发送POST Request失败后可以重新发送,以及如何将用户密码等敏感信息隐藏起来,而不是直接码在代码里,没有使用spring框架。
public void sendNotification() {
try {
URL url = new URL ("https://hello/api");
String Username = "abc";
String Password = "12345";//怎样可以将密码隐藏起来?
HttpURLConnection con = (HttpURLConnection)url.openConnection();
HashMap<String, String> in = new HashMap<>();
input.put("short_description", "Hello");
input.put("title", "Testing");
String jsonStr = JSONValue.toJSONString(input);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json; utf-8");
con.setRequestProperty("Accept", "application/json");
con.setDoOutput(true);
String auth = Username + ":" + Password;
byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.UTF_8));
String authHeaderValue = "Basic " + new String(encodedAuth);
con.setRequestProperty("Authorization", authHeaderValue);
try(OutputStream os = con.getOutputStream()) {
byte[] inputStream = jsonStr.getBytes("utf-8");
os.write(inputStream, 0, inputStream.length);
}
if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
try(BufferedReader br = new BufferedReader(
new InputStreamReader(con.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
LOG.info("Response:" + response.toString());
}
} else {
LOG.error("Failed to send notification.");
//should retry
}
} catch (Exception e) {
LOG.error("Failed to send notification.");
e.printStackTrace();
//should retry
}
}
把下面的语句放在循环语句里面,用连接状态作为循环条件,或者设置循环次数
HttpURLConnection con = (HttpURLConnection)url.openConnection();