Added test case for HttpClient and fixed a small newline issue with the payload

This commit is contained in:
Ziver Koc 2024-12-28 22:10:57 +01:00
parent 28bef3935e
commit 66e7ed4aaf
2 changed files with 137 additions and 22 deletions

View file

@ -1,7 +1,7 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2020 Ziver Koc
* Copyright (c) 2020-2024 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
@ -143,30 +143,38 @@ public class HttpClient implements AutoCloseable {
this.content = content;
}
protected Socket getSocket(int port) throws IOException {
Socket socket = null;
if ("https".equals(url.getProtocol())) {
socket = SSLSocketFactory.getDefault().createSocket(url.getHost(), port);
((SSLSocket)socket).startHandshake();
} else {
socket = new Socket(url.getHost(), port);
}
return socket;
}
/**
* Will send a HTTP request to the target host.
* NOTE: any previous request connections will be closed
*/
public HttpHeader send() throws IOException {
int port = 80;
if (url == null)
if (url == null) {
throw new IllegalArgumentException("No URL defined for request.");
else if (url.getPort() > 0)
} else if (url.getPort() > 0) {
port = url.getPort();
else if ("https".equals(url.getProtocol()))
} else if ("https".equals(url.getProtocol())) {
port = 443;
}
// ---------------------------------
// Create Socket
// ---------------------------------
Socket conn;
if ("https".equals(url.getProtocol())) {
conn = SSLSocketFactory.getDefault().createSocket(url.getHost(), port);
((SSLSocket)conn).startHandshake();
} else {
conn = new Socket(url.getHost(), port);
}
Socket conn = getSocket(port);
// ---------------------------------
// Request
@ -185,17 +193,21 @@ public class HttpClient implements AutoCloseable {
// send payload
if (HttpRequestType.POST.toString().equals(type)) {
String postData;
if (content != null)
postData = content;
else
postData = url.getParameterString();
request.setHeader(HttpHeader.HEADER_CONTENT_LENGTH, "" + postData.length());
request.println();
request.print(postData);
} else
request.println();
String payload = null;
if (content != null) {
payload = content;
} else if (HttpRequestType.POST.toString().equals(type)) {
payload = url.getParameterString();
}
if (payload != null) {
request.setHeader(HttpHeader.HEADER_CONTENT_LENGTH, "" + payload.length());
request.print(payload);
}
// Finish off by sending all buffered data
request.flush();
// ---------------------------------