Example usage for org.springframework.http.client ClientHttpRequest execute

List of usage examples for org.springframework.http.client ClientHttpRequest execute

Introduction

In this page you can find the example usage for org.springframework.http.client ClientHttpRequest execute.

Prototype

ClientHttpResponse execute() throws IOException;

Source Link

Document

Execute this request, resulting in a ClientHttpResponse that can be read.

Usage

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

private static String getJson(RestTemplate restTemplate, String urlString) {
    ClientHttpResponse response = null;/*  w  ww . ja v  a2  s .  c  om*/
    HttpMethod method = null;
    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;//w  w w  .  jav a2 s. co  m
    try {
        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:org.dthume.spring.http.client.httpcomponents.HttpComponentsClientRequestFactoryTest.java

@Test
public void testCreateRequest() throws Exception {
    final URI uri = new URI("http://www.google.com");
    final Header[] responseHeaders = new Header[] {};

    expect(client.execute(isA(HttpUriRequest.class))).andReturn(response);
    expect(response.getAllHeaders()).andReturn(responseHeaders);

    replayMocks();/*  w w w .ja v a 2s. c om*/

    final ClientHttpRequest request = factory.createRequest(uri, HttpMethod.GET);

    final ClientHttpResponse actualResponse = request.execute();

    verify(client, response);
}

From source file:com.cisco.cta.taxii.adapter.httpclient.BasicAuthHttpRequestFactoryTest.java

@Test
public void tryConnectWithBasicAuthentication() throws Exception {
    try {//  w  w  w  .  j a  v a  2  s .c  o  m
        ClientHttpRequest req = factory.createRequest(connSettings.getPollEndpoint().toURI(), HttpMethod.POST);
        req.execute();
        fail("connection must fail");
    } catch (Throwable e) {
        assertThat(e, instanceOf(HttpHostConnectException.class));
    }
    verifyLog(mockAppender, "Re-using cached 'basic' auth scheme for http://localhost:80");
}

From source file:com.cisco.cta.taxii.adapter.httpclient.BasicAuthHttpRequestFactoryTest.java

@Test(expected = SocketTimeoutException.class)
public void timeoutConnection() throws Exception {
    BasicAuthHttpRequestFactory factoryImpl = (BasicAuthHttpRequestFactory) factory;
    factoryImpl.setReadTimeout(10);/* w  w w  . j  a va 2s.  co  m*/
    Thread server = null;
    try (ServerRunnable serverRunnable = new ServerRunnable()) {
        server = new Thread(serverRunnable);
        ClientHttpRequest req = factory.createRequest(connSettings.getPollEndpoint().toURI(), HttpMethod.POST);
        req.execute();
    } finally {
        server.join(10);
    }
}

From source file:com.jaspersoft.jasperserver.api.security.externalAuth.sso.SsoTicketValidatorImpl.java

protected ClientHttpResponse requestTicketValidationFromSsoServer(URI validationUrl)
        throws AuthenticationServiceException {
    try {/*from  w  ww .ja va  2 s.co  m*/
        logger.debug("Requesting SSO token validation from SSO server: " + validationUrl);
        ClientHttpRequest req = getClientHttpRequestFactory().createRequest(validationUrl, HttpMethod.GET);
        ClientHttpResponse res = req.execute();
        return res;
    } catch (IOException e) {
        logger.error("Failed to validate SSO token (" + validationUrl + ")", e);
        throw new AuthenticationServiceException(e.getMessage(), e);
    }
}

From source file:com.springsource.insight.plugin.springweb.http.SimpleClientHttpRequestFactoryCollectionAspectTest.java

@Test
public void testConnectionFactory() throws Exception {
    SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
    factory.setBufferRequestBody(false);
    factory.setConnectTimeout(15 * 1000);
    factory.setReadTimeout(15 * 1000);/* w  w  w.java2s  .c om*/

    URI uri = new URI("http://localhost:" + TEST_PORT + "/testConnectionFactory");
    HttpMethod method = HttpMethod.GET;
    ClientHttpRequest request = factory.createRequest(uri, method);
    ClientHttpResponse response = request.execute();
    assertEquals("Mismatched response code", HttpStatus.OK.value(), response.getRawStatusCode());

    BufferedReader rdr = new BufferedReader(new InputStreamReader(response.getBody()));
    try {
        for (String line = rdr.readLine(); line != null; line = rdr.readLine()) {
            logger.info(line);
        }
    } finally {
        rdr.close();
    }

    Operation op = assertConnectionOperation(uri, method);
    assertExternalResource(op, uri);
}

From source file:com.miserablemind.api.consumer.tradeking.api.impl.StreamingTemplate.java

private ClientHttpResponse executeRequest(HttpMethod method, String url, MultiValueMap<String, String> body)
        throws IOException {
    ClientHttpRequestFactory requestFactory = this.getRestTemplate().getRequestFactory();
    ClientHttpRequest request = requestFactory.createRequest(URI.create(url), method);
    OutputStreamWriter writer = new OutputStreamWriter(request.getBody());
    writer.write(createFormUrlEncodedBodyString(body));
    writer.flush();/*from  w ww  .  j  a va2  s .  c  o  m*/
    return request.execute();
}

From source file:com.card.loop.xyz.controller.LearningObjectController.java

public void uploadAllLOToInformatron() {
    try {/*  ww  w .  j  a v a 2 s.c  om*/
        SimpleClientHttpRequestFactory rf = new SimpleClientHttpRequestFactory();
        ClientHttpRequest req = rf.createRequest(
                URI.create(AppConfig.LOOP_URL + "/loop-XYZ/loop/LO/availableLO"), HttpMethod.GET);
        ClientHttpResponse response = req.execute();

        StringBuilder sb = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(response.getBody()));
        ClientHttpRequest req2 = rf.createRequest(
                URI.create(AppConfig.INFORMATRON_URL + "/InformatronYX/informatron/LO/upload/availableLOs"),
                HttpMethod.POST);
        BufferedWriter req2Writer = new BufferedWriter(new OutputStreamWriter(req2.getBody()));
        String string = br.readLine();
        br.close();

        req2Writer.write(string);
        req2Writer.close();
        req2.getHeaders().add("Content-Type", "application/json");
        System.out.println(string);
        ClientHttpResponse response2 = req2.execute();
        BufferedReader reader = new BufferedReader(new InputStreamReader(response2.getBody()));

        try {
            String str = reader.readLine();
            if (str.equals("true"))
                System.out.println("SUCCESS!!");
            else
                System.err.println("FAILL!!");
        } catch (Exception ex) {
            Logger.getLogger(LearningObjectController.class.getName()).log(Level.SEVERE, null, ex);
        }
    } catch (IOException ex) {
        Logger.getLogger(LearningObjectController.class.getName()).log(Level.SEVERE, null, ex);
    }
}