Co-authored-by: sigonasr2 <sigonasr2@gmail.com>main
parent
12d186a378
commit
67f508ab0a
After Width: | Height: | Size: 326 KiB |
Before Width: | Height: | Size: 210 KiB After Width: | Height: | Size: 386 KiB |
@ -0,0 +1,150 @@ |
|||||||
|
package sig; |
||||||
|
|
||||||
|
import java.io.BufferedReader; |
||||||
|
|
||||||
|
import java.io.File; |
||||||
|
import java.io.FileInputStream; |
||||||
|
import java.io.IOException; |
||||||
|
import java.io.InputStreamReader; |
||||||
|
import java.io.OutputStream; |
||||||
|
import java.io.OutputStreamWriter; |
||||||
|
import java.io.PrintWriter; |
||||||
|
import java.net.HttpURLConnection; |
||||||
|
import java.net.URL; |
||||||
|
import java.net.URLConnection; |
||||||
|
import java.util.ArrayList; |
||||||
|
import java.util.List; |
||||||
|
|
||||||
|
/** |
||||||
|
* This utility class provides an abstraction layer for sending multipart HTTP |
||||||
|
* POST requests to a web server. |
||||||
|
* @author www.codejava.net |
||||||
|
* |
||||||
|
*/ |
||||||
|
public class MultipartUtility { |
||||||
|
private final String boundary; |
||||||
|
private static final String LINE_FEED = "\r\n"; |
||||||
|
private HttpURLConnection httpConn; |
||||||
|
private String charset; |
||||||
|
private OutputStream outputStream; |
||||||
|
private PrintWriter writer; |
||||||
|
|
||||||
|
/** |
||||||
|
* This constructor initializes a new HTTP POST request with content type |
||||||
|
* is set to multipart/form-data |
||||||
|
* @param requestURL |
||||||
|
* @param charset |
||||||
|
* @throws IOException |
||||||
|
*/ |
||||||
|
public MultipartUtility(String requestURL, String charset) |
||||||
|
throws IOException { |
||||||
|
this.charset = charset; |
||||||
|
|
||||||
|
// creates a unique boundary based on time stamp
|
||||||
|
boundary = "===" + System.currentTimeMillis() + "==="; |
||||||
|
|
||||||
|
URL url = new URL(requestURL); |
||||||
|
httpConn = (HttpURLConnection) url.openConnection(); |
||||||
|
httpConn.setUseCaches(false); |
||||||
|
httpConn.setDoOutput(true); // indicates POST method
|
||||||
|
httpConn.setDoInput(true); |
||||||
|
httpConn.setRequestProperty("Content-Type", |
||||||
|
"multipart/form-data; boundary=" + boundary); |
||||||
|
httpConn.setRequestProperty("User-Agent", "CodeJava Agent"); |
||||||
|
httpConn.setRequestProperty("Test", "Bonjour"); |
||||||
|
outputStream = httpConn.getOutputStream(); |
||||||
|
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), |
||||||
|
true); |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* Adds a form field to the request |
||||||
|
* @param name field name |
||||||
|
* @param value field value |
||||||
|
*/ |
||||||
|
public void addFormField(String name, String value) { |
||||||
|
writer.append("--" + boundary).append(LINE_FEED); |
||||||
|
writer.append("Content-Disposition: form-data; name=\"" + name + "\"") |
||||||
|
.append(LINE_FEED); |
||||||
|
writer.append("Content-Type: text/plain; charset=" + charset).append( |
||||||
|
LINE_FEED); |
||||||
|
writer.append(LINE_FEED); |
||||||
|
writer.append(value).append(LINE_FEED); |
||||||
|
writer.flush(); |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* Adds a upload file section to the request |
||||||
|
* @param fieldName name attribute in <input type="file" name="..." /> |
||||||
|
* @param uploadFile a File to be uploaded |
||||||
|
* @throws IOException |
||||||
|
*/ |
||||||
|
public void addFilePart(String fieldName, File uploadFile) |
||||||
|
throws IOException { |
||||||
|
String fileName = uploadFile.getName(); |
||||||
|
writer.append("--" + boundary).append(LINE_FEED); |
||||||
|
writer.append( |
||||||
|
"Content-Disposition: form-data; name=\"" + fieldName |
||||||
|
+ "\"; filename=\"" + fileName + "\"") |
||||||
|
.append(LINE_FEED); |
||||||
|
writer.append( |
||||||
|
"Content-Type: " |
||||||
|
+ URLConnection.guessContentTypeFromName(fileName)) |
||||||
|
.append(LINE_FEED); |
||||||
|
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED); |
||||||
|
writer.flush(); |
||||||
|
|
||||||
|
FileInputStream inputStream = new FileInputStream(uploadFile); |
||||||
|
char[] buffer = new char[1024]; |
||||||
|
String s = new String(buffer); |
||||||
|
byte[] data = s.getBytes("ISO-8859-1"); |
||||||
|
int bytesRead = -1; |
||||||
|
while ((bytesRead = inputStream.read(data)) > 0) { |
||||||
|
outputStream.write(data, 0, bytesRead); |
||||||
|
} |
||||||
|
inputStream.close(); |
||||||
|
|
||||||
|
writer.flush(); |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* Adds a header field to the request. |
||||||
|
* @param name - name of the header field |
||||||
|
* @param value - value of the header field |
||||||
|
*/ |
||||||
|
public void addHeaderField(String name, String value) { |
||||||
|
writer.append(name + ": " + value).append(LINE_FEED); |
||||||
|
writer.flush(); |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* Completes the request and receives response from the server. |
||||||
|
* @return a list of Strings as response in case the server returned |
||||||
|
* status OK, otherwise an exception is thrown. |
||||||
|
* @throws IOException |
||||||
|
*/ |
||||||
|
public List<String> finish() throws IOException { |
||||||
|
List<String> response = new ArrayList<String>(); |
||||||
|
|
||||||
|
writer.flush(); |
||||||
|
writer.append("--" + boundary + "--").append(LINE_FEED); |
||||||
|
writer.close(); |
||||||
|
|
||||||
|
// checks server's status code first
|
||||||
|
int status = httpConn.getResponseCode(); |
||||||
|
if (status == HttpURLConnection.HTTP_OK) { |
||||||
|
BufferedReader reader = new BufferedReader(new InputStreamReader( |
||||||
|
httpConn.getInputStream())); |
||||||
|
String line = null; |
||||||
|
while ((line = reader.readLine()) != null) { |
||||||
|
response.add(line); |
||||||
|
} |
||||||
|
reader.close(); |
||||||
|
httpConn.disconnect(); |
||||||
|
} else { |
||||||
|
System.out.println("Server returned non-OK status: " + status); |
||||||
|
} |
||||||
|
|
||||||
|
return response; |
||||||
|
} |
||||||
|
} |
@ -0,0 +1,7 @@ |
|||||||
|
package sig.exceptions; |
||||||
|
|
||||||
|
public class FailedResponseException extends Exception{ |
||||||
|
public FailedResponseException(String msg) { |
||||||
|
super(msg); |
||||||
|
} |
||||||
|
} |
@ -0,0 +1,99 @@ |
|||||||
|
package sig.requests; |
||||||
|
|
||||||
|
import java.io.IOException; |
||||||
|
import java.net.Authenticator; |
||||||
|
import java.net.PasswordAuthentication; |
||||||
|
import java.net.URI; |
||||||
|
import java.net.URISyntaxException; |
||||||
|
import java.net.http.HttpClient; |
||||||
|
import java.net.http.HttpRequest; |
||||||
|
import java.net.http.HttpResponse; |
||||||
|
import java.net.http.HttpClient.Builder; |
||||||
|
import java.net.http.HttpResponse.BodyHandlers; |
||||||
|
import java.nio.file.Path; |
||||||
|
import java.time.Duration; |
||||||
|
|
||||||
|
import sig.exceptions.FailedResponseException; |
||||||
|
|
||||||
|
public class GETRequest{ |
||||||
|
String url; |
||||||
|
String[] headers; |
||||||
|
long timeout; |
||||||
|
Path file; |
||||||
|
String user=""; |
||||||
|
String pass=""; |
||||||
|
private HttpRequest req; |
||||||
|
private HttpClient client; |
||||||
|
/** |
||||||
|
* @param file The file path info, use this for file downloads or set to null for standard text. |
||||||
|
* @param timeout in milliseconds |
||||||
|
* */ |
||||||
|
public GETRequest(String url, String username, String password, long timeout, Path file, String...headers){ |
||||||
|
this.url = url; |
||||||
|
this.user=username; |
||||||
|
this.pass=password; |
||||||
|
this.headers = headers; |
||||||
|
this.timeout = timeout; |
||||||
|
this.file=file; |
||||||
|
} |
||||||
|
/** |
||||||
|
* @param file The file path info, use this for file downloads or set to null for standard text. |
||||||
|
* @param timeout in milliseconds |
||||||
|
* */ |
||||||
|
public GETRequest(String url, long timeout, Path file, String...headers){ |
||||||
|
this(url,"","",timeout,file,headers); |
||||||
|
} |
||||||
|
/** |
||||||
|
* @param timeout in milliseconds |
||||||
|
* */ |
||||||
|
public GETRequest(String url, long timeout, String...headers){ |
||||||
|
this(url,timeout,null,headers); |
||||||
|
} |
||||||
|
public GETRequest(String url){ |
||||||
|
this(url,30000,null); |
||||||
|
} |
||||||
|
public HttpResponse<?> run() throws FailedResponseException { |
||||||
|
build(); |
||||||
|
try { |
||||||
|
if (file==null) { |
||||||
|
return client.send(req,BodyHandlers.ofString()); |
||||||
|
} else { |
||||||
|
return client.send(req,BodyHandlers.ofFile(file)); |
||||||
|
} |
||||||
|
} catch (IOException | InterruptedException e) { |
||||||
|
e.printStackTrace(); |
||||||
|
} |
||||||
|
throw new FailedResponseException("No proper response returned. THIS SHOULD NOT BE HAPPENING!"); |
||||||
|
} |
||||||
|
protected java.net.http.HttpRequest.Builder finalizeRequestPreBuild(java.net.http.HttpRequest.Builder requestBuild) throws FailedResponseException { |
||||||
|
return requestBuild.GET(); |
||||||
|
} |
||||||
|
protected Builder finalizeClientPreBuild(Builder clientBuild) { |
||||||
|
return clientBuild; |
||||||
|
} |
||||||
|
protected void build(){ |
||||||
|
boolean AUTH_REQUIRED=user.length()>0&&pass.length()>0; |
||||||
|
try { |
||||||
|
java.net.http.HttpRequest.Builder requestBuild=HttpRequest.newBuilder(new URI(url)) |
||||||
|
.version(HttpClient.Version.HTTP_2) |
||||||
|
.timeout(Duration.ofMillis(timeout)); |
||||||
|
if (headers!=null&&headers.length>0) { |
||||||
|
requestBuild.headers(headers); |
||||||
|
} |
||||||
|
req = finalizeRequestPreBuild(requestBuild).build(); |
||||||
|
Builder clientBuild=HttpClient.newBuilder() |
||||||
|
.followRedirects(HttpClient.Redirect.ALWAYS); |
||||||
|
if (AUTH_REQUIRED) { |
||||||
|
clientBuild.authenticator(new Authenticator() { |
||||||
|
@Override |
||||||
|
protected PasswordAuthentication getPasswordAuthentication() { |
||||||
|
return new PasswordAuthentication(user,pass.toCharArray()); |
||||||
|
} |
||||||
|
}); |
||||||
|
} |
||||||
|
client = finalizeClientPreBuild(clientBuild).build(); |
||||||
|
} catch (URISyntaxException | FailedResponseException e) { |
||||||
|
e.printStackTrace(); |
||||||
|
} |
||||||
|
} |
||||||
|
} |
@ -0,0 +1,131 @@ |
|||||||
|
package sig.requests; |
||||||
|
|
||||||
|
import java.io.File; |
||||||
|
import java.io.FileNotFoundException; |
||||||
|
import java.io.IOException; |
||||||
|
import java.net.URI; |
||||||
|
import java.net.http.HttpHeaders; |
||||||
|
import java.net.http.HttpRequest; |
||||||
|
import java.net.http.HttpResponse; |
||||||
|
import java.net.http.HttpClient.Builder; |
||||||
|
import java.net.http.HttpClient.Version; |
||||||
|
import java.nio.charset.StandardCharsets; |
||||||
|
import java.nio.file.Path; |
||||||
|
import java.util.List; |
||||||
|
import java.util.Optional; |
||||||
|
|
||||||
|
import javax.net.ssl.SSLSession; |
||||||
|
|
||||||
|
import sig.MultipartUtility; |
||||||
|
import sig.exceptions.FailedResponseException; |
||||||
|
|
||||||
|
public class POSTRequest extends GETRequest{ |
||||||
|
|
||||||
|
String body = ""; |
||||||
|
Path uploadFile = null; |
||||||
|
|
||||||
|
public POSTRequest(String url, String body, String username, String password, long timeout, Path outputFile, String... headers) { |
||||||
|
super(url, username, password, timeout, outputFile, headers); |
||||||
|
this.body=body; |
||||||
|
} |
||||||
|
|
||||||
|
public POSTRequest(String url, String body, long timeout, Path outputFile, String... headers) { |
||||||
|
super(url, timeout, outputFile, headers); |
||||||
|
this.body=body; |
||||||
|
} |
||||||
|
|
||||||
|
public POSTRequest(String url, String body, long timeout, String... headers) { |
||||||
|
super(url, timeout, headers); |
||||||
|
this.body=body; |
||||||
|
} |
||||||
|
|
||||||
|
public POSTRequest(String url, String body) { |
||||||
|
super(url); |
||||||
|
this.body=body; |
||||||
|
} |
||||||
|
|
||||||
|
public POSTRequest(String url, Path uploadFile) { |
||||||
|
super(url); |
||||||
|
this.uploadFile=uploadFile; |
||||||
|
} |
||||||
|
@Override |
||||||
|
public HttpResponse<?> run() throws FailedResponseException { |
||||||
|
if (uploadFile!=null) { |
||||||
|
String charset = "ISO-8859-1"; |
||||||
|
File file = uploadFile.toFile(); |
||||||
|
String requestURL = url; |
||||||
|
|
||||||
|
try { |
||||||
|
MultipartUtility multipart = new MultipartUtility(requestURL, charset); |
||||||
|
|
||||||
|
multipart.addHeaderField("User-Agent", "SIG HTTPCLIENT"); |
||||||
|
|
||||||
|
multipart.addFilePart("fileUpload", file); |
||||||
|
|
||||||
|
List<String> response = multipart.finish(); |
||||||
|
return new HttpResponse<String>(){ |
||||||
|
@Override |
||||||
|
public int statusCode() { |
||||||
|
return 0; |
||||||
|
} |
||||||
|
@Override |
||||||
|
public HttpRequest request() { |
||||||
|
return null; |
||||||
|
} |
||||||
|
@Override |
||||||
|
public Optional<HttpResponse<String>> previousResponse() { |
||||||
|
return null; |
||||||
|
} |
||||||
|
@Override |
||||||
|
public HttpHeaders headers() { |
||||||
|
return null; |
||||||
|
} |
||||||
|
@Override |
||||||
|
public String body() { |
||||||
|
StringBuilder sb = new StringBuilder(); |
||||||
|
for (String s : response) { |
||||||
|
sb.append(s); |
||||||
|
} |
||||||
|
return sb.toString(); |
||||||
|
} |
||||||
|
@Override |
||||||
|
public Optional<SSLSession> sslSession() { |
||||||
|
return null; |
||||||
|
} |
||||||
|
@Override |
||||||
|
public URI uri() { |
||||||
|
return null; |
||||||
|
} |
||||||
|
@Override |
||||||
|
public Version version() { |
||||||
|
return null; |
||||||
|
} |
||||||
|
}; |
||||||
|
} catch (IOException ex) { |
||||||
|
System.err.println(ex); |
||||||
|
throw new FailedResponseException("Could not send response for POST File upload. THIS SHOULD NOT BE HAPPENING!"); |
||||||
|
} |
||||||
|
} else { |
||||||
|
return super.run(); |
||||||
|
} |
||||||
|
} |
||||||
|
@Override |
||||||
|
protected java.net.http.HttpRequest.Builder finalizeRequestPreBuild( |
||||||
|
java.net.http.HttpRequest.Builder requestBuild) throws FailedResponseException{ |
||||||
|
requestBuild.headers("Content-Type","application/json"); |
||||||
|
try { |
||||||
|
return file!=null?requestBuild.POST(HttpRequest.BodyPublishers.ofFile(file)): |
||||||
|
body.length()>0?requestBuild.POST(HttpRequest.BodyPublishers.ofString(body)): |
||||||
|
requestBuild.POST(HttpRequest.BodyPublishers.noBody()); |
||||||
|
} catch (FileNotFoundException e) { |
||||||
|
e.printStackTrace(); |
||||||
|
} |
||||||
|
throw new FailedResponseException("Could not complete request build. THIS SHOULD NOT BE HAPPENING!"); |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
protected Builder finalizeClientPreBuild(Builder clientBuild) { |
||||||
|
return clientBuild; |
||||||
|
} |
||||||
|
|
||||||
|
} |
Loading…
Reference in new issue