Fixed endpoint not assigned in thread and added connection and read timeout to the HTTP connection

This commit is contained in:
Mauro Mugnaini 2020-06-25 11:41:04 +02:00
parent 9eb4ad8bf7
commit 9b888a796b
1 changed files with 23 additions and 11 deletions

View File

@ -44,10 +44,14 @@ public class HTTPEventSender implements EventSender {
public class HTTPost implements Runnable {
private static final int CONNECTION_TIMEOUT = 10000;
private static final int READ_TIMEOUT = 5000;
private URL endpoint;
private String jsonString;
public HTTPost(URL endpoint, String jsonString) {
this.endpoint = endpoint;
this.jsonString = jsonString;
}
@ -61,14 +65,22 @@ public class HTTPEventSender implements EventSender {
if (log.isTraceEnabled()) {
log.trace("Performing HTTP POST");
}
HttpURLConnection con = (HttpURLConnection) endpoint.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Method", "POST");
con.setRequestProperty("Authorization", token.getAsBearer());
OutputStream os = con.getOutputStream();
HttpURLConnection connection = (HttpURLConnection) endpoint.openConnection();
connection.setConnectTimeout(CONNECTION_TIMEOUT);
if (log.isTraceEnabled()) {
log.trace("HTTP connection timeout set to: " + connection.getConnectTimeout());
}
connection.setReadTimeout(READ_TIMEOUT);
if (log.isTraceEnabled()) {
log.trace("HTTP connection Read timeout set to: " + connection.getReadTimeout());
}
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Method", "POST");
connection.setRequestProperty("Authorization", token.getAsBearer());
OutputStream os = connection.getOutputStream();
if (log.isTraceEnabled()) {
log.trace("Sending event JSON");
}
@ -76,7 +88,7 @@ public class HTTPEventSender implements EventSender {
os.close();
StringBuilder sb = new StringBuilder();
int httpResultCode = con.getResponseCode();
int httpResultCode = connection.getResponseCode();
if (log.isTraceEnabled()) {
log.trace("HTTP Response code: " + httpResultCode);
}
@ -86,10 +98,10 @@ public class HTTPEventSender implements EventSender {
boolean ok = true;
InputStreamReader isr = null;
if (httpResultCode == HttpURLConnection.HTTP_OK) {
isr = new InputStreamReader(con.getInputStream(), "UTF-8");
isr = new InputStreamReader(connection.getInputStream(), "UTF-8");
} else {
ok = false;
isr = new InputStreamReader(con.getErrorStream(), "UTF-8");
isr = new InputStreamReader(connection.getErrorStream(), "UTF-8");
}
BufferedReader br = new BufferedReader(isr);
String line = null;