78 lines
2.6 KiB
Java
Raw Normal View History

package container;
2022-01-13 23:14:36 +01:00
import helper.Tuple;
import java.io.BufferedReader;
import java.io.DataOutputStream;
2022-01-25 19:19:18 +01:00
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class HttpRequest {
2022-01-13 23:14:36 +01:00
public static String TOKEN = "";
public Tuple<Integer, String> sendPostRequest(String urlString, String urlParameters, boolean sendAuth) throws Exception {
byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
int postDataLength = postData.length;
URL url = new URL(urlString);
2022-01-25 19:19:18 +01:00
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
2022-01-25 19:19:18 +01:00
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", Integer.toString(postDataLength));
connection.setUseCaches(false);
2022-01-11 17:12:37 +01:00
if(sendAuth){
2022-01-25 19:19:18 +01:00
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Authorization", "Bearer " + TOKEN);
2022-01-11 17:12:37 +01:00
}
2022-01-25 19:19:18 +01:00
try (DataOutputStream writer = new DataOutputStream(connection.getOutputStream())) {
writer.write(postData);
}
2022-01-25 19:19:18 +01:00
return getHttpTuple(connection);
}
public Tuple<Integer, String> sendGetRequest(String urlString) throws Exception {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
int status = connection.getResponseCode();
return getHttpTuple(connection);
}
private Tuple<Integer, String> getHttpTuple(HttpURLConnection connection) throws IOException {
int status = connection.getResponseCode();
2022-01-13 23:14:36 +01:00
String inputLine;
StringBuilder content = new StringBuilder();
BufferedReader in;
2022-01-13 23:14:36 +01:00
if (status == 200) {
2022-01-29 11:44:25 +01:00
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
} else {
2022-01-29 11:44:25 +01:00
in = new BufferedReader(new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8));
2022-01-13 23:14:36 +01:00
}
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
2022-01-13 23:14:36 +01:00
in.close();
2022-01-25 19:19:18 +01:00
connection.disconnect();
2022-01-13 23:14:36 +01:00
return new Tuple<>(status, content.toString());
}
}