HttpJsonPoster { public void post(String json) { try { URL url = new URL(reportingConfig.url()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(1_000); connection.setReadTimeout(10_000); connection.setRequestMethod("POST"); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-Type", "application/json"); String version = Optional.ofNullable(this.getClass().getPackage().getImplementationVersion()) .orElse("0.0.0"); connection.setRequestProperty("User-Agent", "docker-compose-rule/" + version); connection.setDoOutput(true); PrintWriter body = new PrintWriter(connection.getOutputStream()); body.println(json); body.close(); connection.connect(); int status = connection.getResponseCode(); if (status >= 400) { String error = CharStreams.toString(new InputStreamReader( connection.getErrorStream(), StandardCharsets.UTF_8)); throw new RuntimeException("Posting json failed. Error is: " + error); } connection.disconnect(); } catch (Exception e) { log.error("Failed to post report", e); } } HttpJsonPoster(ReportingConfig reportingConfig); void post(String json);  }
@Test public void can_post_webhook() { wireMockRule.stubFor(post("/some/path").willReturn(status(200))); when(reportingConfig.url()).thenReturn(String.format("http: String json = "{\"foo\":\"bar\"}"; httpJsonPoster.post(json); wireMockRule.verify(postRequestedFor(urlPathEqualTo("/some/path")).withRequestBody(containing(json))); }