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; } }