Example usage for org.springframework.web.client RestTemplate setRequestFactory

List of usage examples for org.springframework.web.client RestTemplate setRequestFactory

Introduction

In this page you can find the example usage for org.springframework.web.client RestTemplate setRequestFactory.

Prototype

@Override
public void setRequestFactory(ClientHttpRequestFactory requestFactory) 

Source Link

Usage

From source file:comsat.sample.tomcat.SampleTomcatTwoConnectorsApplicationTests.java

@Test
public void testHello() throws Exception {
    RestTemplate template = new RestTemplate();
    final MySimpleClientHttpRequestFactory factory = new MySimpleClientHttpRequestFactory(
            new HostnameVerifier() {

                @Override/*from   ww w .j  ava 2 s.  co m*/
                public boolean verify(final String hostname, final SSLSession session) {
                    return true; // these guys are alright by me...
                }
            });
    template.setRequestFactory(factory);

    ResponseEntity<String> entity = template.getForEntity("http://localhost:" + this.port + "/hello",
            String.class);
    assertEquals(HttpStatus.OK, entity.getStatusCode());
    assertEquals("hello", entity.getBody());

    ResponseEntity<String> httpsEntity = template
            .getForEntity("https://localhost:" + this.context.getBean("port") + "/hello", String.class);
    assertEquals(HttpStatus.OK, httpsEntity.getStatusCode());
    assertEquals("hello", httpsEntity.getBody());
}

From source file:org.cloudfoundry.identity.client.UaaContextFactory.java

protected UaaContext authenticateSaml2BearerAssertion(final TokenRequest request) {
    RestTemplate template = new RestTemplate();
    if (request.isSkipSslValidation()) {
        template.setRequestFactory(getNoValidatingClientHttpRequestFactory());
    }//from  ww w .  j a v a  2  s  .  c  o  m
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
    form.add(OAuth2Utils.CLIENT_ID, request.getClientId());
    form.add("client_secret", request.getClientSecret());
    form.add(OAuth2Utils.GRANT_TYPE, "urn:ietf:params:oauth:grant-type:saml2-bearer");
    form.add("assertion", request.getAuthCodeAPIToken());

    ResponseEntity<CompositeAccessToken> token = template.exchange(request.getTokenEndpoint(), HttpMethod.POST,
            new HttpEntity<>(form, headers), CompositeAccessToken.class);
    return new UaaContextImpl(request, null, token.getBody());
}

From source file:org.cloudfoundry.identity.client.UaaContextFactory.java

protected UaaContext fetchTokenFromCode(final TokenRequest request) {
    String clientBasicAuth = getClientBasicAuthHeader(request);

    RestTemplate template = new RestTemplate();
    if (request.isSkipSslValidation()) {
        template.setRequestFactory(getNoValidatingClientHttpRequestFactory());
    }/*w w w  .jav a 2  s.  com*/
    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.AUTHORIZATION, clientBasicAuth);
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
    form.add(OAuth2Utils.GRANT_TYPE, "authorization_code");
    form.add(OAuth2Utils.REDIRECT_URI, request.getRedirectUri().toString());
    String responseType = "token";
    if (request.wantsIdToken()) {
        responseType += " id_token";
    }
    form.add(OAuth2Utils.RESPONSE_TYPE, responseType);
    form.add("code", request.getAuthorizationCode());

    ResponseEntity<CompositeAccessToken> token = template.exchange(request.getTokenEndpoint(), HttpMethod.POST,
            new HttpEntity<>(form, headers), CompositeAccessToken.class);
    return new UaaContextImpl(request, null, token.getBody());
}

From source file:cz.muni.fi.mushroomhunter.restclient.MushroomDeleteSwingWorker.java

@Override
protected Integer doInBackground() throws Exception {
    int selectedRow = restClient.getTblMushroom().getSelectedRow();
    RestTemplate restTemplate = new RestTemplate();

    String plainCreds = RestClient.USER_NAME + ":" + RestClient.PASSWORD;
    byte[] plainCredsBytes = plainCreds.getBytes();
    byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
    String base64Creds = new String(base64CredsBytes);

    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Basic " + base64Creds);

    HttpEntity<String> request = new HttpEntity<>(headers);

    restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory() {
        @Override/*from   w  w w . j  ava 2s  . c  o m*/
        protected HttpUriRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) {
            if (HttpMethod.DELETE == httpMethod) {
                return new HttpEntityEnclosingDeleteRequest(uri);
            }
            return super.createHttpUriRequest(httpMethod, uri);
        }
    });

    restTemplate.exchange(
            RestClient.SERVER_URL + "pa165/rest/mushroom/" + RestClient.getMushroomIDs().get(selectedRow),
            HttpMethod.DELETE, request, MushroomDto.class);

    RestClient.getMushroomIDs().remove(selectedRow);
    return selectedRow;
}

From source file:cz.muni.fi.mushroomhunter.restclient.LocationDeleteSwingWorker.java

@Override
protected Integer doInBackground() throws Exception {
    int selectedRow = restClient.getTblLocation().getSelectedRow();
    RestTemplate restTemplate = new RestTemplate();

    String plainCreds = RestClient.USER_NAME + ":" + RestClient.PASSWORD;
    byte[] plainCredsBytes = plainCreds.getBytes();
    byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
    String base64Creds = new String(base64CredsBytes);

    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Basic " + base64Creds);

    HttpEntity<String> request = new HttpEntity<>(headers);

    restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory() {
        @Override// w  w  w .  j  a  v  a2  s  .co  m
        protected HttpUriRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) {
            if (HttpMethod.DELETE == httpMethod) {
                return new HttpEntityEnclosingDeleteRequest(uri);
            }
            return super.createHttpUriRequest(httpMethod, uri);
        }
    });

    restTemplate.exchange(
            RestClient.SERVER_URL + "pa165/rest/location/" + RestClient.getLocationIDs().get(selectedRow),
            HttpMethod.DELETE, request, LocationDto.class);

    RestClient.getLocationIDs().remove(selectedRow);
    return selectedRow;
}

From source file:org.cloudfoundry.client.lib.rest.CloudControllerClientV1.java

/**
 * Upload an app using the legacy API used for older vcap versions like Micro Cloud Foundry 1.1 and older
 * As of Micro Cloud Foundry 1.2 and for any recent CloudFoundry.com deployment the current method of setting
 * the content type as JSON works fine.//  w  w  w. j a v  a 2s .c  o m
 *
 * @param path app path
 * @param entity HttpEntity for the payload
 * @param appName name of app
 * @throws HttpServerErrorException
 */
private void uploadAppUsingLegacyApi(String path, HttpEntity<?> entity, String appName)
        throws HttpServerErrorException {
    RestTemplate legacyRestTemplate = new RestTemplate();
    legacyRestTemplate.setRequestFactory(this.getRestTemplate().getRequestFactory());
    legacyRestTemplate.setErrorHandler(new ErrorHandler());
    legacyRestTemplate.setMessageConverters(getLegacyMessageConverters());
    legacyRestTemplate.put(path, entity, appName);
}

From source file:org.cloudfoundry.identity.uaa.login.RemoteUaaController.java

public RemoteUaaController(Environment environment, RestTemplate restTemplate) {

    // The default java.net client doesn't allow you to handle 4xx responses
    restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory() {
        @Override/*from w  ww  . j  a  va 2  s  .c  o m*/
        public HttpClient getHttpClient() {
            return HttpClientBuilder.create().useSystemProperties().disableCookieManagement().build();
        }
    });
    restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
        @Override
        public boolean hasError(ClientHttpResponse response) throws IOException {
            HttpStatus statusCode = response.getStatusCode();
            return statusCode.series() == HttpStatus.Series.SERVER_ERROR;
        }
    });
    this.environment = environment;
    defaultTemplate = restTemplate;
    initProperties();
}

From source file:ru.anr.base.facade.web.api.RestClient.java

/**
 * Special initialization of {@link RestTemplate} - used to apply some
 * settings for existing RestTemplates./*from   w w  w.j  av  a  2  s  .  c o  m*/
 * 
 * @param template
 *            {@link RestTemplate} or its
 * @return Updated RestTemplate
 */
public RestTemplate initRest(RestTemplate template) {

    // 1. Set up ssl settings
    HttpClient client = "https".equals(schema) ? buildSSLClient()
            : HttpClients.custom().setDefaultCookieStore(store).build();

    template.setRequestFactory(new HttpComponentsClientHttpRequestFactory(client) {

        @Override
        protected void postProcessHttpRequest(HttpUriRequest request) {

            super.postProcessHttpRequest(request);
        }

    });

    // 2. Error handler
    template.setErrorHandler(new DefaultResponseErrorHandler());

    return template;
}

From source file:org.springframework.social.linkedin.api.impl.LinkedInTemplate.java

private void registerJsonFormatInterceptor() {
    RestTemplate restTemplate = getRestTemplate();
    if (interceptorsSupported) {
        List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
        interceptors.add(new JsonFormatInterceptor());
    } else {/*from w ww.j  a v  a 2s  . co m*/
        // for Spring 3.0.x where interceptors aren't supported
        ClientHttpRequestFactory originalRequestFactory = restTemplate.getRequestFactory();
        JsonFormatHeaderRequestFactory newRequestFactory = new JsonFormatHeaderRequestFactory(
                originalRequestFactory);
        restTemplate.setRequestFactory(newRequestFactory);
    }
}