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

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

Introduction

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

Prototype

@Override
    public <T> ResponseEntity<T> exchange(URI url, HttpMethod method, @Nullable HttpEntity<?> requestEntity,
            ParameterizedTypeReference<T> responseType) throws RestClientException 

Source Link

Usage

From source file:com.example.user.UserEndpoint.java

public static void main(String[] args) {
    final ObjectMapper objectMapper = new ObjectMapper().registerModule(new Jackson2HalModule())
            .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
            .setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
    final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(objectMapper);
    converter.setSupportedMediaTypes(Collections.singletonList(MediaTypes.HAL_JSON));
    final RestTemplate restTemplate = new RestTemplate(Collections.singletonList(converter));
    final ResponseEntity<PagedResources<Resource<UserEntity>>> entity = restTemplate.exchange(
            "http://localhost:5000/db-app/users", HttpMethod.GET, null,
            new ParameterizedTypeReference<PagedResources<Resource<UserEntity>>>() {
            });//from   ww  w .j a  v a2 s. com
    System.out.println(entity.getStatusCode());
    final PagedResources<Resource<UserEntity>> body = entity.getBody();
    System.out.println(body);
    final Collection<Resource<UserEntity>> contents = body.getContent();
    final List<UserEntity> userEntities = contents.stream().map(Resource::getContent).collect(toList());
}

From source file:br.edu.unifesspa.lcc.indexer.teste.java

public static void main(String[] args) {
    int assunto = 215;
    RestTemplate rt = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Bearer d724997c-ba1d-42aa-8ed3-40a8a590558e");
    HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
    try {//from ww w  .j a  v  a  2 s .  c om
        System.out.println("Comeando a inserir os Inputs do assunto: " + assunto);
        ResponseEntity<domain.Input_presenteDTO[]> input = rt.exchange(
                "http://xingu.lcc.unifesspa.edu.br:8080/api/input_presentes/getInputPresenteByAssantoId/"
                        + assunto,
                HttpMethod.GET, entity, Input_presenteDTO[].class);
        System.out.println("Fez o download do assunto: " + assunto);
        System.out.println("Tamano input: " + input.getBody().length + "  Assunto: " + assunto);
    } catch (Exception e) {

    }
}

From source file:com.apress.prospringintegration.web.MultipartHttpClient.java

public static void main(String[] args) {
    RestTemplate template = new RestTemplate();
    String uri = "http://localhost:8080/http-adapter-1.0.0/inboundMultipartAdapter.html";
    Resource picture = new ClassPathResource("com/apress/prospringintegration/web/test.png");
    MultiValueMap map = new LinkedMultiValueMap();
    map.add("name", "John Smith");
    map.add("picture", picture);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(new MediaType("multipart", "form-data"));
    HttpEntity request = new HttpEntity(map, headers);
    ResponseEntity<?> httpResponse = template.exchange(uri, HttpMethod.POST, request, null);
    System.out.println("Status: " + httpResponse.getStatusCode().name());
}

From source file:com.hatta.consumer.App.java

@SuppressWarnings({ "unchecked" })
private static AuthTokenInfo sendTokenRequest() {
    RestTemplate restTemplate = new RestTemplate();

    HttpEntity<String> request = new HttpEntity<String>(getHeadersWithClientCredentials());
    ResponseEntity<Object> response = restTemplate.exchange(AUTH_SERVER_URI + QPM_PASSWORD_GRANT,
            HttpMethod.POST, request, Object.class);
    LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>) response.getBody();
    AuthTokenInfo tokenInfo = null;//from  w w w .  j  a  v  a  2 s .c o m

    if (map != null) {
        tokenInfo = new AuthTokenInfo();
        tokenInfo.setAccess_token((String) map.get("access_token"));
        tokenInfo.setToken_type((String) map.get("token_type"));
        tokenInfo.setRefresh_token((String) map.get("refresh_token"));
        tokenInfo.setExpires_in((int) map.get("expires_in"));
        tokenInfo.setScope((String) map.get("scope"));
        System.out.println(tokenInfo);
        System.out.println("access_token =" + map.get("access_token") + ", token_type=" + map.get("token_type")
                + ", refresh_token=" + map.get("refresh_token") + ", expires_in=" + map.get("expires_in")
                + ", scope=" + map.get("scope"));
        ;
    } else {
        System.out.println("No user exist----------");

    }
    return tokenInfo;
}

From source file:com.hatta.consumer.App.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private static void listAllCustomers(AuthTokenInfo tokenInfo) {

    Assert.notNull(tokenInfo, "Authenticate first please......");

    RestTemplate restTemplate = new RestTemplate();
    ////from  w  ww  .j  a  va2s .c  o  m
    //        HttpHeaders headers = new HttpHeaders();
    //        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    HttpEntity<String> request = new HttpEntity<String>(getHeaders());
    ResponseEntity<List> response = restTemplate.exchange(
            REST_SERVICE_URI + "/api/user" + QPM_ACCESS_TOKEN + tokenInfo.getAccess_token(), HttpMethod.GET,
            request, List.class);
    List<LinkedHashMap<String, Object>> customerMap = (List<LinkedHashMap<String, Object>>) response.getBody();
    //         
    //        List<LinkedHashMap<String, Object>> customerMap = restTemplate.getForObject(REST_SERVICE_URI + "/api/user", List.class);

    if (customerMap != null) {
        System.out.println("Retrieve all customers:");
        for (LinkedHashMap<String, Object> map : customerMap) {
            System.out.println("Customer : id=" + map.get("id") + ", Name=" + map.get("name") + ", Address="
                    + map.get("email") + ", Email=" + map.get("password") + map.get("enabled"));
        }
    } else {
        System.out.println("No customer exist----------");
    }
}

From source file:com.rsa.redchallenge.standaloneapp.utils.RestInteractor.java

/**
 * Function to call POST interface for a REST server
 *
 * @param path path of the interface in the REST server to be called
 * @return returns the response/* ww  w  . j a v a2s .  c om*/
 */
public static String performPost(String path, Map<String, Object> params, String jsessionId)
        throws SecurityException {

    RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
    setFactory(restTemplate);
    HttpHeaders headers = new HttpHeaders();
    headers.add("Cookie", "RSA_SA_LICENSE=true; " + jsessionId);
    String uri = populatePath(params, path);
    logger.info("performing post request for uri:" + uri);
    HttpEntity<String> request = new HttpEntity<>(headers);

    try {
        String result = restTemplate.exchange(uri, HttpMethod.GET, request, String.class).getBody();
        return result;
    } catch (HttpClientErrorException e) {
        e.printStackTrace();
        throw e;
    }
}

From source file:com.goldengekko.meetr.itest.AuthITest.java

public static JConnection registerToken(RestTemplate restTemplate) {

    LinkedMultiValueMap<String, String> request = getOAuth2Request();
    HttpEntity requestEntity = new HttpEntity(request, getHttpBasicHeader());

    // register federated token first
    //        JConnection fedResponse = restTemplate.postForObject(API_URL + "/federated/v11", 
    //                 requestEntity, JConnection.class);
    ResponseEntity<JConnection> fedResponse = restTemplate.exchange(API_URL + "/federated/v11", HttpMethod.POST,
            requestEntity, JConnection.class);

    //assertEquals(HttpStatus.CREATED, fedResponse.getStatusCode());
    assertNotNull("JConnection ", fedResponse.getBody());
    return fedResponse.getBody();
}

From source file:org.apache.servicecomb.demo.jaxrs.client.JaxrsClient.java

private static void testExchange(RestTemplate template, String cseUrlPrefix) {
    HttpHeaders headers = new HttpHeaders();
    headers.add("Accept", MediaType.APPLICATION_JSON);
    Person person = new Person();
    person.setName("world");
    HttpEntity<Person> requestEntity = new HttpEntity<>(person, headers);
    ResponseEntity<Person> resEntity = template.exchange(cseUrlPrefix + "/compute/sayhello", HttpMethod.POST,
            requestEntity, Person.class);
    TestMgr.check("hello world", resEntity.getBody());

    ResponseEntity<String> resEntity2 = template.exchange(cseUrlPrefix + "/compute/addstring?s=abc&s=def",
            HttpMethod.DELETE, null, String.class);
    TestMgr.check("abcdef", resEntity2.getBody());
}

From source file:org.apache.servicecomb.demo.jaxrs.client.JaxrsClient.java

@SuppressWarnings({ "rawtypes" })
private static void testValidatorExchangeFail(RestTemplate template, String cseUrlPrefix) {
    HttpHeaders headers = new HttpHeaders();
    headers.add("Accept", MediaType.APPLICATION_JSON);
    Student student = new Student();
    student.setName("");
    student.setAge(25);/* w  w  w .  ja  v  a  2  s.co  m*/
    boolean isExcep = false;
    try {
        HttpEntity<Student> requestEntity = new HttpEntity<>(student, headers);
        template.exchange(cseUrlPrefix + "/sayhello", HttpMethod.POST, requestEntity, Student.class);
    } catch (InvocationException e) {
        isExcep = true;
        TestMgr.check(400, e.getStatus().getStatusCode());
        TestMgr.check(Status.BAD_REQUEST, e.getReasonPhrase());
        // Message dependends on locale, so just check the short part.
        Map data = (Map) e.getErrorData();
        TestMgr.check(true, data.get("message").toString().contains("propertyPath=sayHello.student.age"));
    }
    TestMgr.check(true, isExcep);
}

From source file:projekat.rest_client.Test.java

public static void main2(String[] args)
        throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {

    String uri = "https://localhost:8443/secure/rest/places";
    RestTemplateFactory factory = new RestTemplateFactory();
    factory.afterPropertiesSet();/*from   www .  j  a  v  a 2  s .c  o  m*/
    RestTemplate restTemplate = factory.getObject();
    //        restTemplate.exchange(uri, HttpMethod.GET, new HttpEntity<T>(createHeaders("marko", "marko")), List.class);
    HttpClient httpClient = factory.getAuth().getHttpClient();
    TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] certificate, String authType) {
            return true;
        }
    };
    SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy, ALLOW_ALL_HOSTNAME_VERIFIER);
    httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 8443, sf));
    ResponseEntity<List> exchange = restTemplate.exchange(uri, HttpMethod.POST,
            new HttpEntity<>(createHeaders("marko", "marko")), List.class);

    List body = exchange.getBody();
    for (Object object : body) {
        System.out.println("Mesto: " + object);
    }

    System.out.println("******************");
    ResponseEntity<List> forEntity = restTemplate.getForEntity(uri, List.class);
    List body1 = forEntity.getBody();
    for (Object object : body1) {
        System.out.println("Mesto: " + object);
    }

}