summaryrefslogtreecommitdiffstats
path: root/src/main/java/org/openslx/taskmanager/tasks/HttpRequest.java
blob: bcc6b96e8800f2f65960a3d336d43897ca36b4f9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
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;

	}

}