/** * Sends a GET request and returns the response. * * @param endpoint The endpoint to send the request to. * @param headers Any additional headers to send with this request. You can use {@link * org.apache.http.HttpHeaders} constants for header names. * @return A {@link Path} to the downloaded content, if any. * @throws IOException If an error occurs. * @see java.nio.file.Files#probeContentType(Path) */ public Response<Path> get(Endpoint endpoint, NameValuePair... headers) throws IOException { // Create the request HttpGet get = new HttpGet(endpoint.url()); get.setHeaders(combineHeaders(headers)); Path tempFile = null; // Send the request and process the response try (CloseableHttpResponse response = httpClient().execute(get)) { if (response.getStatusLine().getStatusCode() != HttpStatus.OK_200) { return null; } // If bad response return null // Request the content HttpEntity entity = response.getEntity(); // Download the content to a temporary file if (entity != null) { tempFile = Files.createTempFile("download", "file"); try (InputStream input = entity.getContent(); OutputStream output = Files.newOutputStream(tempFile)) { IOUtils.copy(input, output); } } return new Response<>(response.getStatusLine(), tempFile); } }
/** * Deserialises the given {@link CloseableHttpResponse} to the specified type. * * @param response The response. * @return The response as a String, or null if the response does not contain an entity. * @throws IOException If an error occurs. */ private String getResponseString(CloseableHttpResponse response) throws IOException { String body = null; HttpEntity entity = response.getEntity(); if (entity != null) { try (InputStream inputStream = entity.getContent()) { body = IOUtils.toString(inputStream); } } else { EntityUtils.consume(entity); } return body; }
/** * Deserialises the given {@link CloseableHttpResponse} to the specified type. * * @param response The response. * @param responseClass The type to deserialise to. * @param <T> The type to deserialise to. * @return The deserialised response, or null if the response does not contain an entity. * @throws IOException If an error occurs. */ private <T> T deserialiseResponseMessage(CloseableHttpResponse response, Class<T> responseClass) throws IOException { T body = null; HttpEntity entity = response.getEntity(); if (entity != null) { try (InputStream inputStream = entity.getContent()) { try { body = Serialiser.deserialise(inputStream, responseClass); } catch (JsonSyntaxException e) { // This can happen if an error HTTP code is received and the // body of the response doesn't contain the expected object: body = null; } } } else { EntityUtils.consume(entity); } return body; }