Example usage for org.springframework.http.client ClientHttpResponse close

List of usage examples for org.springframework.http.client ClientHttpResponse close

Introduction

In this page you can find the example usage for org.springframework.http.client ClientHttpResponse close.

Prototype

@Override
void close();

Source Link

Document

Close this response, freeing any resources created.

Usage

From source file:org.eclipse.cft.server.core.internal.client.CloudFoundryClientFactory.java

private static String getJson(RestTemplate restTemplate, String urlString) {
    ClientHttpResponse response = null;
    HttpMethod method = null;//from   w  w w  .ja  va2  s  .  c o m
    try {
        method = HttpMethod.GET;

        URI url = new UriTemplate(urlString).expand();
        ClientHttpRequest request = restTemplate.getRequestFactory().createRequest(url, method);

        List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
        acceptableMediaTypes.add(MediaType.APPLICATION_JSON);
        request.getHeaders().setAccept(acceptableMediaTypes);
        //if (requestCallback != null) {
        //   requestCallback.doWithRequest(request);
        //}
        response = request.execute();
        if (response.getBody() != null) {
            HttpMessageConverterExtractor<String> extractor = new HttpMessageConverterExtractor<String>(
                    String.class, restTemplate.getMessageConverters());
            String data = extractor.extractData(response);
            return data;
        }
        ;
    } catch (IOException ex) {
        throw new ResourceAccessException(
                "I/O error on " + method.name() + " request for \"" + urlString + "\":" + ex.getMessage(), ex);
    } finally {
        if (response != null) {
            response.close();
        }
    }
    return null;
}

From source file:de.blizzy.documentr.system.Downloader.java

String getTextFromUrl(String url, Charset encoding) throws IOException {
    ClientHttpResponse response = null;
    try {/*  ww  w. j av  a  2s.  c o  m*/
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout((int) TIMEOUT);
        requestFactory.setReadTimeout((int) TIMEOUT);
        ClientHttpRequest request = requestFactory.createRequest(URI.create(url), HttpMethod.GET);
        response = request.execute();
        HttpStatus status = response.getStatusCode();
        if (status.series() == Series.SUCCESSFUL) {
            return IOUtils.toString(response.getBody(), encoding);
        }
    } finally {
        if (response != null) {
            response.close();
        }
    }
    return null;
}

From source file:cz.jirutka.spring.http.client.cache.internal.SizeLimitedHttpResponseReader.java

/**
 * Reads the original {@link ClientHttpResponse} to memory, if possible,
 * and returns a serializable copy. If the response's body size exceeds the
 * specified {@code maxBodySize} limit, then it throws
 * {@link ResponseSizeLimitExceededException} with a reconstructed response
 * that combines an already read bytes in memory and the original response.
 *
 * @param response The original response to read.
 * @return An in-memory copy of the original response.
 * @throws ResponseSizeLimitExceededException When the response's body size
 *         exceeds the specified {@code maxBodySize} limit.
 * @throws IOException/*from  w w w  .  ja v  a2s  . c o m*/
 */
public InMemoryClientHttpResponse readResponse(ClientHttpResponse response)
        throws ResponseSizeLimitExceededException, IOException {

    Assert.notNull(response, "response must not be null");

    InputStream bodyStream = response.getBody();
    ByteArrayOutputStream out = new ByteArrayOutputStream(initialCapacity());

    long bytesTotal = 0;
    byte[] buffer = new byte[bufferSize];
    int bytesRead = -1;

    while ((bytesRead = bodyStream.read(buffer)) != -1) {
        out.write(buffer, 0, bytesRead);
        bytesTotal += bytesRead;

        if (bytesTotal > maxBodySize - 1) {
            throw new ResponseSizeLimitExceededException(createCombinedResponse(response, out, bodyStream));
        }
    }
    response.close();

    return createInMemoryResponse(response, out);
}

From source file:org.fao.geonet.util.XslUtil.java

/**
 * Returns the HTTP code  or error message if error occurs during URL connection.
 *
 * @param url       The URL to ckeck.//from   w w  w  . j a  va  2s  . c  om
 * @param tryNumber the number of remaining tries.
 */
public static String getUrlStatus(String url, int tryNumber) {
    if (tryNumber < 1) {
        // protect against redirect loops
        return "ERR_TOO_MANY_REDIRECTS";
    }
    HttpHead head = new HttpHead(url);
    GeonetHttpRequestFactory requestFactory = ApplicationContextHolder.get()
            .getBean(GeonetHttpRequestFactory.class);
    ClientHttpResponse response = null;
    try {
        response = requestFactory.execute(head, new Function<HttpClientBuilder, Void>() {
            @Nullable
            @Override
            public Void apply(@Nullable HttpClientBuilder originalConfig) {
                RequestConfig.Builder config = RequestConfig.custom().setConnectTimeout(1000)
                        .setConnectionRequestTimeout(3000).setSocketTimeout(5000);
                RequestConfig requestConfig = config.build();
                originalConfig.setDefaultRequestConfig(requestConfig);

                return null;
            }
        });
        //response = requestFactory.execute(head);
        if (response.getRawStatusCode() == HttpStatus.SC_BAD_REQUEST
                || response.getRawStatusCode() == HttpStatus.SC_METHOD_NOT_ALLOWED
                || response.getRawStatusCode() == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
            // the website doesn't support HEAD requests. Need to do a GET...
            response.close();
            HttpGet get = new HttpGet(url);
            response = requestFactory.execute(get);
        }

        if (response.getStatusCode().is3xxRedirection() && response.getHeaders().containsKey("Location")) {
            // follow the redirects
            return getUrlStatus(response.getHeaders().getFirst("Location"), tryNumber - 1);
        }

        return String.valueOf(response.getRawStatusCode());
    } catch (IOException e) {
        Log.error(Geonet.GEONETWORK, "IOException validating  " + url + " URL. " + e.getMessage(), e);
        return e.getMessage();
    } finally {
        if (response != null) {
            response.close();
        }
    }
}

From source file:org.fao.geonet.api.mapservers.GeoServerRest.java

/**
 * @param method      e.g. 'POST', 'GET', 'PUT' or 'DELETE'
 * @param urlParams   REST API parameter
 * @param postData    XML data/*from  w w  w. j  a  v  a  2 s  . c  o  m*/
 * @param file        File to upload
 * @param contentType type of content in case of post data or file updload.
 */
public @CheckReturnValue int sendREST(String method, String urlParams, String postData, Path file,
        String contentType, Boolean saveResponse) throws IOException {

    response = "";
    String url = this.restUrl + urlParams;
    if (Log.isDebugEnabled(LOGGER_NAME)) {
        Log.debug(LOGGER_NAME, "url:" + url);
        Log.debug(LOGGER_NAME, "method:" + method);
        if (postData != null)
            Log.debug(LOGGER_NAME, "postData:" + postData);
    }

    HttpRequestBase m;
    if (method.equals(METHOD_PUT)) {
        m = new HttpPut(url);
        if (file != null) {
            ((HttpPut) m)
                    .setEntity(new PathHttpEntity(file, ContentType.create(contentType, Constants.ENCODING)));
        }

        if (postData != null) {
            final StringEntity entity = new StringEntity(postData,
                    ContentType.create(contentType, Constants.ENCODING));
            ((HttpPut) m).setEntity(entity);
        }
    } else if (method.equals(METHOD_DELETE)) {
        m = new HttpDelete(url);
    } else if (method.equals(METHOD_POST)) {
        m = new HttpPost(url);
        if (postData != null) {
            final StringEntity entity = new StringEntity(postData,
                    ContentType.create(contentType, Constants.ENCODING));
            ((HttpPost) m).setEntity(entity);
        }
    } else {
        m = new HttpGet(url);
    }

    if (contentType != null && !"".equals(contentType)) {
        m.setHeader("Content-type", contentType);
    }

    m.setConfig(RequestConfig.custom().setAuthenticationEnabled(true).build());

    // apparently this is needed to preemptively send the auth, for servers that dont require it but
    // dont send the same data if you're authenticated or not.
    try {
        m.addHeader(new BasicScheme().authenticate(new UsernamePasswordCredentials(username, password), m));
    } catch (AuthenticationException a) {
        Log.warning(LOGGER_NAME, "Failed to add the authentication Header, error is: " + a.getMessage());
    }
    ;

    final ClientHttpResponse httpResponse = factory.execute(m,
            new UsernamePasswordCredentials(username, password), AuthScope.ANY);

    try {
        status = httpResponse.getRawStatusCode();
        if (Log.isDebugEnabled(LOGGER_NAME)) {
            Log.debug(LOGGER_NAME, "status:" + status);
        }
        if (saveResponse) {
            this.response = IOUtils.toString(httpResponse.getBody());
        }
    } finally {
        httpResponse.close();
    }

    return status;
}

From source file:org.springframework.boot.web.servlet.server.AbstractServletWebServerFactoryTests.java

@Test
public void mimeType() throws Exception {
    FileCopyUtils.copy("test", new FileWriter(this.temporaryFolder.newFile("test.xxcss")));
    AbstractServletWebServerFactory factory = getFactory();
    factory.setDocumentRoot(this.temporaryFolder.getRoot());
    MimeMappings mimeMappings = new MimeMappings();
    mimeMappings.add("xxcss", "text/css");
    factory.setMimeMappings(mimeMappings);
    this.webServer = factory.getWebServer();
    this.webServer.start();
    ClientHttpResponse response = getClientResponse(getLocalUrl("/test.xxcss"));
    assertThat(response.getHeaders().getContentType().toString()).isEqualTo("text/css");
    response.close();
}

From source file:org.springframework.boot.actuate.autoconfigure.EndpointWebMvcAutoConfigurationTests.java

private void assertContent(String scheme, String url, int port, Object expected) throws Exception {

    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
            new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build());
    HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
            httpClient);//from   ww w  . j  a  v  a2  s  .  c  o  m
    ClientHttpRequest request = requestFactory.createRequest(new URI(scheme + "://localhost:" + port + url),
            HttpMethod.GET);
    try {
        ClientHttpResponse response = request.execute();
        if (HttpStatus.NOT_FOUND.equals(response.getStatusCode())) {
            throw new FileNotFoundException();
        }
        try {
            String actual = StreamUtils.copyToString(response.getBody(), Charset.forName("UTF-8"));
            if (expected instanceof Matcher) {
                assertThat(actual).is(Matched.by((Matcher<?>) expected));
            } else {
                assertThat(actual).isEqualTo(expected);
            }
        } finally {
            response.close();
        }
    } catch (Exception ex) {
        if (expected == null) {
            if (SocketException.class.isInstance(ex) || FileNotFoundException.class.isInstance(ex)) {
                return;
            }
        }
        throw ex;
    }
}

From source file:org.openflamingo.uploader.handler.HttpToLocalHandler.java

/**
 * HTTP  URL? ./*from ww w .  j  av  a2 s .  com*/
 *
 * @param http HTTP
 * @return HTTP Response String
 * @throws Exception HTTP ? ?? ? ? 
 */
private String getResponse(Http http) throws Exception {
    jobLogger.info("HTTP URL?    ?  .");

    String url = jobContext.getValue(http.getUrl());
    String method = jobContext.getValue(http.getMethod().getType());
    String body = jobContext.getValue(http.getBody());

    jobLogger.info("HTTP URL Information :");
    jobLogger.info("\tURL = {}", url);
    jobLogger.info("\tMethod = {}", method);

    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
    ClientHttpRequest request = null;
    if ("POST".equals(method)) {
        request = factory.createRequest(new java.net.URI(url), POST);
    } else {
        request = factory.createRequest(new java.net.URI(url), GET);
    }

    if (http.getHeaders() != null && http.getHeaders().getHeader().size() > 0) {
        List<Header> header = http.getHeaders().getHeader();
        jobLogger.info("HTTP Header :", new String[] {});
        for (Header h : header) {
            String name = h.getName();
            String value = jobContext.getValue(h.getValue());
            request.getHeaders().add(name, value);
            jobLogger.info("\t{} = {}", name, value);
        }
    }

    String responseBodyAsString = null;
    ClientHttpResponse response = null;
    try {
        response = request.execute();
        responseBodyAsString = new String(FileCopyUtils.copyToByteArray(response.getBody()),
                Charset.defaultCharset());
        jobLogger.debug("HTTP ? ?  ? .\n{}", responseBodyAsString);
        jobLogger.info("HTTP ? . ?  '{}({})'.",
                response.getStatusText(), response.getRawStatusCode());
        if (response.getRawStatusCode() != HttpStatus.ORDINAL_200_OK) {
            throw new SystemException(ExceptionUtils.getMessage(
                    "HTTP URL ? . ? OK  '{}({})'  ? .",
                    response.getStatusText(), response.getRawStatusCode()));
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new SystemException(
                ExceptionUtils.getMessage("HTTP URL ? . ? : {}",
                        ExceptionUtils.getRootCause(ex).getMessage()),
                ex);
    } finally {
        try {
            response.close();
        } catch (Exception ex) {
            // Ignored
        }
    }
    return responseBodyAsString;
}