From 1dc9445bc5a5d7c840d2a3c74bc2e94df0abda8f Mon Sep 17 00:00:00 2001 From: Simon Rettberg Date: Wed, 15 Feb 2023 14:51:47 +0100 Subject: [HttpRequest] Add task We use this for the HTTP transport in the eventlog module of slx-admin --- .../org/openslx/taskmanager/tasks/HttpRequest.java | 95 ++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 src/main/java/org/openslx/taskmanager/tasks/HttpRequest.java diff --git a/src/main/java/org/openslx/taskmanager/tasks/HttpRequest.java b/src/main/java/org/openslx/taskmanager/tasks/HttpRequest.java new file mode 100644 index 0000000..bcc6b96 --- /dev/null +++ b/src/main/java/org/openslx/taskmanager/tasks/HttpRequest.java @@ -0,0 +1,95 @@ +package org.openslx.taskmanager.tasks; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.charset.StandardCharsets; + +import org.openslx.satserver.util.Util; +import org.openslx.taskmanager.api.AbstractTask; + +import com.google.gson.annotations.Expose; + +/** + * For async HTTP calls + */ +public class HttpRequest extends AbstractTask +{ + + private Status status = new Status(); + + @Expose + private String url; + + @Expose + private String postData; + + @Expose + private String contentType; + + @Override + protected boolean initTask() + { + this.setStatusObject( status ); + return !Util.isEmpty( this.url ); + } + + @Override + protected boolean execute() + { + HttpURLConnection http = null; + try { + byte[] out = null; + URL url = new URL( this.url ); + http = (HttpURLConnection)url.openConnection(); + if ( this.postData != null ) { + http.setRequestMethod( "POST" ); + http.setDoOutput( true ); + out = this.postData.getBytes( StandardCharsets.UTF_8 ); + if ( this.contentType != null ) { + http.setRequestProperty( "Content-Type", this.contentType ); + } + http.setFixedLengthStreamingMode( out.length ); + } + // + http.connect(); + // + if ( out != null ) { + try ( OutputStream os = http.getOutputStream() ) { + os.write( out ); + } + } + try ( InputStream is = http.getInputStream() ) { + // Throw data away so the connection can be reused + byte[] buffer = new byte[ 10000 ]; + while ( is.read( buffer ) > 0 ) { + } + } + + } catch ( IOException e ) { + status.error = e.getMessage(); + if ( http != null ) { + try ( InputStream es = http.getErrorStream() ) { + // Throw data away so the connection can be reused + byte[] buffer = new byte[ 10000 ]; + while ( es.read( buffer ) > 0 ) { + } + status.error += " (" + http.getResponseCode() + " " + http.getResponseMessage() + ")"; + } catch ( IOException e1 ) { + } + } + return false; + } + return true; + } + + static class Status + { + + String error; + + } + +} -- cgit v1.2.3-55-g7522