ParseContentType implements HttpFunction { @Override public void service(HttpRequest request, HttpResponse response) throws IOException { String name; String contentType = request.getContentType().orElse(""); switch (contentType) { case "application/json": JsonObject body = gson.fromJson(request.getReader(), JsonObject.class); if (body.has("name")) { name = body.get("name").getAsString(); break; } case "application/octet-stream": name = new String(Base64.getDecoder().decode(request.getInputStream().readAllBytes()), StandardCharsets.UTF_8); break; case "text/plain": name = request.getReader().readLine(); break; case "application/x-www-form-urlencoded": Optional<String> nameParam = request.getFirstQueryParameter("name"); if (nameParam.isPresent()) { name = nameParam.get(); break; } default: response.setStatusCode(HttpURLConnection.HTTP_BAD_REQUEST); return; } if (name != null) { var writer = new PrintWriter(response.getWriter()); writer.printf("Hello %s!", name); } }  @Override void service(HttpRequest request, HttpResponse response);  }
@Test public void parseContentTypeTest_json() throws IOException { String requestJson = gson.toJson(Map.of("name", "John")); BufferedReader bodyReader = new BufferedReader(new StringReader(requestJson)); when(request.getContentType()).thenReturn(Optional.of("application/json")); when(request.getReader()).thenReturn(bodyReader); new ParseContentType().service(request, response); writerOut.flush(); assertThat(responseOut.toString()).contains("Hello John!"); }
@Test public void parseContentTypeTest_base64() throws IOException { when(request.getContentType()).thenReturn(Optional.of("application/octet-stream")); byte[] b64Body = Base64.getEncoder().encode("John".getBytes(StandardCharsets.UTF_8)); InputStream bodyInputStream = new ByteArrayInputStream(b64Body); when(request.getInputStream()).thenReturn(bodyInputStream); new ParseContentType().service(request, response); writerOut.flush(); assertThat(responseOut.toString()).contains("Hello John!"); }
@Test public void parseContentTypeTest_text() throws IOException { when(request.getContentType()).thenReturn(Optional.of("text/plain")); BufferedReader bodyReader = new BufferedReader(new StringReader("John")); when(request.getReader()).thenReturn(bodyReader); new ParseContentType().service(request, response); writerOut.flush(); assertThat(responseOut.toString()).contains("Hello John!"); }
@Test public void parseContentTypeTest_form() throws IOException { when(request.getContentType()).thenReturn(Optional.of("application/x-www-form-urlencoded")); when(request.getFirstQueryParameter("name")).thenReturn(Optional.of("John")); new ParseContentType().service(request, response); writerOut.flush(); assertThat(responseOut.toString()).contains("Hello John!"); }