DefaultConnection implements Connection { @Override public JSON readJsonResponse() throws AcmeException { assertConnectionIsOpen(); if (conn.getContentLength() == 0) { throw new AcmeProtocolException("Empty response"); } String contentType = AcmeUtils.getContentType(conn.getHeaderField(CONTENT_TYPE_HEADER)); if (!(MIME_JSON.equals(contentType) || MIME_JSON_PROBLEM.equals(contentType))) { throw new AcmeProtocolException("Unexpected content type: " + contentType); } try { InputStream in = conn.getResponseCode() < 400 ? conn.getInputStream() : conn.getErrorStream(); if (in == null) { throw new AcmeProtocolException("JSON response is empty"); } JSON result = JSON.parse(in); LOG.debug("Result JSON: {}", result.toString()); return result; } catch (IOException ex) { throw new AcmeNetworkException(ex); } } DefaultConnection(HttpConnector httpConnector); @Override void resetNonce(Session session); @Override int sendRequest(URL url, Session session, @Nullable ZonedDateTime ifModifiedSince); @Override int sendCertificateRequest(URL url, Login login); @Override int sendSignedPostAsGetRequest(URL url, Login login); @Override int sendSignedRequest(URL url, JSONBuilder claims, Login login); @Override int sendSignedRequest(URL url, JSONBuilder claims, Session session, KeyPair keypair); @Override JSON readJsonResponse(); @Override List<X509Certificate> readCertificates(); @Override void handleRetryAfter(String message); @Override @Nullable String getNonce(); @Override @Nullable URL getLocation(); @Override Optional<ZonedDateTime> getLastModified(); @Override Optional<ZonedDateTime> getExpiration(); @Override Collection<URL> getLinks(String relation); @Override void close();  }
@Test public void testReadJsonResponse() throws Exception { String jsonData = "{\n\"foo\":123,\n\"bar\":\"a-string\"\n}\n"; when(mockUrlConnection.getHeaderField("Content-Type")).thenReturn("application/json"); when(mockUrlConnection.getContentLength()).thenReturn(jsonData.length()); when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); when(mockUrlConnection.getInputStream()).thenReturn(new ByteArrayInputStream(jsonData.getBytes("utf-8"))); try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { conn.conn = mockUrlConnection; JSON result = conn.readJsonResponse(); assertThat(result, is(notNullValue())); assertThat(result.keySet(), hasSize(2)); assertThat(result.get("foo").asInt(), is(123)); assertThat(result.get("bar").asString(), is("a-string")); } verify(mockUrlConnection).getHeaderField("Content-Type"); verify(mockUrlConnection).getContentLength(); verify(mockUrlConnection).getResponseCode(); verify(mockUrlConnection).getInputStream(); verifyNoMoreInteractions(mockUrlConnection); }