private CloseableHttpClient createClientInstance() { final RequestConfig requestConfig = RequestConfig.copy(RequestConfig.DEFAULT) .setConnectionRequestTimeout((int) config.getConnectTimeout().toMillis()) .setSocketTimeout((int) config.getConnectTimeout().toMillis()) .build(); final List<Header> headers = new ArrayList<>(1); headers.add( new BasicHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType())); return HttpClients.custom() .setDefaultRequestConfig(requestConfig) .setDefaultHeaders(headers) .build(); }
private URI requestURI(final String path, final List<NameValuePair> queryParams) { try { return new URIBuilder(config.getBaseURI()).setPath(path).setParameters(queryParams).build(); } catch (URISyntaxException use) { String paramString = ""; for (final NameValuePair nvp : queryParams) { paramString += "'" + nvp.getName() + "' -> '" + nvp.getValue() + "'"; } throw new IllegalArgumentException( "Invalid URI for path='" + path + "' params=" + paramString, use); } }
private <T> T executeRequest(final HttpUriRequest request, final ResponseHandler<T> handler) throws IOException { final CloseableHttpClient client = createClientInstance(); try { final CloseableHttpResponse response = client.execute(request); // Wrap the response in a buffer to facilitate error handlers re-playing the content if the // response // size is smaller than the max allowable buffer if (response.getEntity().getContentLength() >= 0 && response.getEntity().getContentLength() < config.getMaxBufferSize()) { EntityUtils.updateEntity(response, new BufferedHttpEntity(response.getEntity())); } // Explicit check for the authorization status of the API key if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { throw new HyppoAuthException(config); } try { log.debug( "{} - {} : {}", request.getMethod(), request.getURI().getPath(), response.getStatusLine().getStatusCode()); return handler.handleResponse(response); } finally { IOUtils.closeQuietly(response); } } catch (Exception e) { log.error( "{} - {} : FAILED - {}", request.getMethod(), request.getURI().getPath(), e.toString()); throw e; } finally { IOUtils.closeQuietly(client); } }