public String get( String urlAsString, String username, String password )
    throws IOException, AuthenticationException {

    HttpGet getMethod = new HttpGet( urlAsString );
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse httpResponse = null;
    InputStreamReader inputStreamReader = null;
    try {
      httpClient = openHttpClient( username, password );
      httpResponse = httpClient.execute( getMethod );
      int statusCode = httpResponse.getStatusLine().getStatusCode();
      StringBuilder bodyBuffer = new StringBuilder();

      if ( statusCode != -1 ) {
        if ( statusCode != HttpStatus.SC_UNAUTHORIZED ) {
          // the response
          inputStreamReader = new InputStreamReader( httpResponse.getEntity().getContent() );

          int c;
          while ( ( c = inputStreamReader.read() ) != -1 ) {
            bodyBuffer.append( (char) c );
          }
          inputStreamReader.close();

        } else {
          throw new AuthenticationException();
        }
      }

      // Display response
      return bodyBuffer.toString();
    } finally {
      if ( httpResponse != null ) {
        httpResponse.close();
      }
      if ( inputStreamReader != null ) {
        inputStreamReader.close();
      }
      if ( httpClient != null ) {
        httpClient.close();
      }
    }
  }
@Test
  public void httpClientGetsClosed() throws IOException, AuthenticationException {
    CloseableHttpClient httpClient = Mockito.mock( CloseableHttpClient.class );
    CloseableHttpResponse response = Mockito.mock( CloseableHttpResponse.class );
    HTTPProtocol httpProtocol = new HTTPProtocol() {
      @Override CloseableHttpClient openHttpClient( String username, String password ) {
        return httpClient;
      }
    };
    String urlAsString = "http://url/path";
    when( httpClient.execute( argThat( matchesGet() ) ) ).thenReturn( response );
    StatusLine statusLine = new BasicStatusLine( new ProtocolVersion( "http", 2, 0 ), HttpStatus.SC_OK, "blah" );
    BasicHttpEntity entity = new BasicHttpEntity();
    String content = "plenty of mocks for this test";
    entity.setContent( new ByteArrayInputStream( content.getBytes() ) );
    when( response.getEntity() ).thenReturn( entity );
    when( response.getStatusLine() ).thenReturn( statusLine );
    assertEquals( content, httpProtocol.get( urlAsString, "", "" ) );
    verify( httpClient ).close();
  }