Client.java (2893B)
1 package com.wimdupont.client; 2 3 import com.fasterxml.jackson.databind.ObjectMapper; 4 5 import java.io.BufferedReader; 6 import java.io.IOException; 7 import java.io.InputStreamReader; 8 import java.io.OutputStream; 9 import java.io.OutputStreamWriter; 10 import java.net.HttpURLConnection; 11 import java.net.URI; 12 import java.nio.charset.StandardCharsets; 13 import java.util.Map; 14 import java.util.Optional; 15 16 public class Client { 17 18 private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); 19 private static final Map<String, String> POST_HEADER_MAP = Map.of("Content-type", "application/json"); 20 21 public static ObjectMapper getObjectMapper() { 22 return OBJECT_MAPPER; 23 } 24 25 public static <T> Optional<T> get(String url, Class<T> responseClazz) { 26 try { 27 HttpURLConnection connection = (HttpURLConnection) URI.create(url).toURL().openConnection(); 28 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream())); 29 StringBuilder stringBuilder = new StringBuilder(); 30 for (String line = bufferedReader.readLine(); line != null; line = bufferedReader.readLine()) { 31 stringBuilder.append(line); 32 } 33 return Optional.of(OBJECT_MAPPER.readValue(stringBuilder.toString(), responseClazz)); 34 } catch (Exception e) { 35 System.out.println(e.getMessage()); 36 return Optional.empty(); 37 } 38 } 39 40 public static <T> Optional<T> post(String url, Class<T> responseClazz, String body) { 41 try { 42 HttpURLConnection connection = (HttpURLConnection) URI.create(url).toURL().openConnection(); 43 connection.setRequestMethod("POST"); 44 POST_HEADER_MAP.forEach(connection::setRequestProperty); 45 connection.setDoOutput(true); 46 return Optional.of(OBJECT_MAPPER.readValue(sendAndGetResponse(body, connection), responseClazz)); 47 } catch (Exception e) { 48 System.out.println(e.getMessage()); 49 return Optional.empty(); 50 } 51 } 52 53 private static String sendAndGetResponse(String body, 54 HttpURLConnection connection) throws IOException { 55 OutputStream outStream = connection.getOutputStream(); 56 OutputStreamWriter outStreamWriter = new OutputStreamWriter(outStream, StandardCharsets.UTF_8); 57 outStreamWriter.write(body); 58 outStreamWriter.flush(); 59 outStreamWriter.close(); 60 outStream.close(); 61 62 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream())); 63 StringBuilder stringBuilder = new StringBuilder(); 64 for (String line = bufferedReader.readLine(); line != null; line = bufferedReader.readLine()) { 65 stringBuilder.append(line); 66 } 67 return stringBuilder.toString(); 68 } 69 }