Skip to content

Instantly share code, notes, and snippets.

@1moita
Created May 14, 2024 23:00
Show Gist options
  • Save 1moita/eee98b633b607d863297fefac9dd192b to your computer and use it in GitHub Desktop.
Save 1moita/eee98b633b607d863297fefac9dd192b to your computer and use it in GitHub Desktop.
public final class HTTPUtil {
private static Map<String, String> properties = new HashMap<>();
public static void withRequestProperty(String key, String value) {
properties.put(key, value);
}
public static void removeProperty(String key) {
properties.remove(key);
}
public static JsonObject makeRequest(String url, String method) {
JsonObject result = null;
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod(method);
connection.setDoOutput(false);
properties.forEach(connection::setRequestProperty);
try(BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
StringBuilder response = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null) {
response.append(line.trim());
}
result = (JsonObject) new JsonParser().parse(response.toString());
}
connection.disconnect();
} catch(IOException exception) {
Logger.log(Logger.Level.SEVERE, "[ctx:e-%s]", exception.getLocalizedMessage());
}
properties.clear();
return result;
}
public static JsonObject makeRequest(String url, String method, JsonObject body) {
JsonObject result = null;
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod(method);
connection.setDoOutput(true);
properties.forEach(connection::setRequestProperty);
try(DataOutputStream writer = new DataOutputStream(connection.getOutputStream())) {
byte[] input = body.toString().getBytes(StandardCharsets.UTF_8);
writer.write(input, 0, input.length);
}
try(BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
StringBuilder response = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null) {
response.append(line.trim());
}
result = (JsonObject) new JsonParser().parse(response.toString());
}
connection.disconnect();
} catch(IOException exception) {
Logger.log(Logger.Level.SEVERE, "[ctx:e-%s]", exception.getLocalizedMessage());
}
properties.clear();
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment