public String getToken() throws IOException {
        LOGGER.debug("[Agent Registration] Using URL {} to get a token.", tokenURL);

        HttpRequestBase getTokenRequest = (HttpRequestBase) RequestBuilder.get(tokenURL)
                .addParameter("uuid", agentRegistry.uuid())
                .build();

        try (CloseableHttpResponse response = httpClient.execute(getTokenRequest)) {
            if (response.getStatusLine().getStatusCode() == SC_OK) {
                LOGGER.info("The server has generated token for the agent.");
                return responseBody(response);
            } else {
                LOGGER.error("[Agent Registration] Got status {} from GoCD", response.getStatusLine());

                String error = Optional.ofNullable(ContentType.get(response.getEntity()))
                    .filter(ct -> ContentType.TEXT_HTML.getMimeType().equals(ct.getMimeType()))
                    .map(ignore -> "<non-machine HTML response>")
                    .orElseGet(() -> responseBody(response));
                throw new RuntimeException(String.format("Agent registration could not acquire token due to %s: %s", response.getStatusLine(), error));
            }
        } finally {
            getTokenRequest.releaseConnection();
        }
    }
@Test
    void shouldErrorOutIfServerRejectTheRequest() throws Exception {
        final CloseableHttpResponse httpResponse = mock(CloseableHttpResponse.class);

        when(agentRegistry.uuid()).thenReturn("agent-uuid");
        when(httpClient.execute(any(HttpRequestBase.class))).thenReturn(httpResponse);
        when(httpResponse.getEntity()).thenReturn(new StringEntity("A token has already been issued for this agent."));
        when(httpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("https", 1, 2), SC_UNPROCESSABLE_ENTITY, null));

        assertThatCode(() -> tokenRequester.getToken())
                .isInstanceOf(RuntimeException.class)
                .hasMessage("Agent registration could not acquire token due to https/1.2 422 : A token has already been issued for this agent.");
    }