Created
May 14, 2024 23:00
-
-
Save 1moita/eee98b633b607d863297fefac9dd192b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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