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:org.cloudfoundry.identity.uaa.login.feature.AutologinIT.java

@Test
public void testSimpleAutologinFlow() throws Exception {
    HttpHeaders headers = getAppBasicAuthHttpHeaders();

    LinkedMultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
    requestBody.add("username", testAccounts.getUserName());
    requestBody.add("password", testAccounts.getPassword());

    //generate an autologin code with our credentials
    ResponseEntity<Map> autologinResponseEntity = restOperations.exchange(baseUrl + "/autologin",
            HttpMethod.POST, new HttpEntity<>(requestBody, headers), Map.class);
    String autologinCode = (String) autologinResponseEntity.getBody().get("code");

    //start the authorization flow - this will issue a login event
    //by using the autologin code
    String authorizeUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/authorize")
            .queryParam("redirect_uri", appUrl).queryParam("response_type", "code")
            .queryParam("client_id", "app").queryParam("code", autologinCode).build().toUriString();

    //rest template that does NOT follow redirects
    RestTemplate template = new RestTemplate(new DefaultIntegrationTestConfig.HttpClientFactory());
    headers.remove("Authorization");
    ResponseEntity<Map> authorizeResponse = template.exchange(authorizeUrl, HttpMethod.GET,
            new HttpEntity<>(new HashMap<String, String>(), headers), Map.class);

    //we are now logged in. retrieve the JSESSIONID
    List<String> cookies = authorizeResponse.getHeaders().get("Set-Cookie");
    assertEquals(1, cookies.size());//from  ww w. j  a  v a 2 s .co  m
    headers = getAppBasicAuthHttpHeaders();
    headers.add("Cookie", cookies.get(0));

    //if we receive a 200, then we must approve our scopes
    if (HttpStatus.OK == authorizeResponse.getStatusCode()) {
        authorizeUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/authorize")
                .queryParam("user_oauth_approval", "true").build().toUriString();
        authorizeResponse = template.exchange(authorizeUrl, HttpMethod.POST,
                new HttpEntity<>(new HashMap<String, String>(), headers), Map.class);
    }

    //approval is complete, we receive a token code back
    assertEquals(HttpStatus.FOUND, authorizeResponse.getStatusCode());
    List<String> location = authorizeResponse.getHeaders().get("Location");
    assertEquals(1, location.size());
    String newCode = location.get(0).substring(location.get(0).indexOf("code=") + 5);

    //request a token using our code
    String tokenUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/token")
            .queryParam("response_type", "token").queryParam("grant_type", "authorization_code")
            .queryParam("code", newCode).queryParam("redirect_uri", appUrl).build().toUriString();

    ResponseEntity<Map> tokenResponse = template.exchange(tokenUrl, HttpMethod.POST,
            new HttpEntity<>(new HashMap<String, String>(), headers), Map.class);
    assertEquals(HttpStatus.OK, tokenResponse.getStatusCode());

    //here we must reset our state. we do that by following the logout flow.
    headers.clear();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    ResponseEntity<Void> loginResponse = restOperations.exchange(baseUrl + "/login.do", HttpMethod.POST,
            new HttpEntity<>(requestBody, headers), Void.class);
    cookies = loginResponse.getHeaders().get("Set-Cookie");
    assertEquals(1, cookies.size());
    headers.clear();
    headers.add("Cookie", cookies.get(0));
    restOperations.exchange(baseUrl + "/profile", HttpMethod.GET, new HttpEntity<>(null, headers), Void.class);

    String revokeApprovalsUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/profile").build()
            .toUriString();
    requestBody.clear();
    requestBody.add("clientId", "app");
    requestBody.add("delete", "");
    ResponseEntity<Void> revokeResponse = template.exchange(revokeApprovalsUrl, HttpMethod.POST,
            new HttpEntity<>(requestBody, headers), Void.class);
    assertEquals(HttpStatus.FOUND, revokeResponse.getStatusCode());
}

From source file:org.zaizi.SensefyResourceApplicationTests.java

@Test
public void testRootPathAuthorized() {
    RestTemplate template = new TestRestTemplate();
    final HttpHeaders headers = new HttpHeaders();
    String accessToken = TestOAuthUtils.getDefOAuth2AccessToken();
    TestOAuthUtils.addOAuth2AccessTokenToHeader(headers, accessToken);
    HttpEntity<String> httpEntity = new HttpEntity<>(headers);
    ResponseEntity<String> response = template.exchange(baseTestServerUrl(), HttpMethod.GET, httpEntity,
            String.class);
    Assert.assertEquals(HttpStatus.OK, response.getStatusCode());
}

From source file:com.ge.predix.test.utils.PrivilegeHelper.java

public BaseSubject[] listSubjects(final RestTemplate restTemplate, final String acsUrl,
        final HttpHeaders headers) {
    URI uri = URI.create(acsUrl + ACS_SUBJECT_API_PATH);
    ResponseEntity<BaseSubject[]> response = restTemplate.exchange(uri, HttpMethod.GET,
            new HttpEntity<>(headers), BaseSubject[].class);
    return response.getBody();
}

From source file:id.co.teleanjar.ppobws.restclient.RestClientService.java

public Map<String, Object> inquiry(String idpel, String idloket, String merchantCode) throws IOException {
    String uri = "http://localhost:8080/ppobws/api/produk";
    RestTemplate restTemplate = new RestTemplate();

    HttpHeaders headers = createHeaders("superuser", "passwordku");
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(uri).queryParam("idpel", idpel)
            .queryParam("idloket", idloket).queryParam("merchantcode", merchantCode);
    HttpEntity<?> entity = new HttpEntity<>(headers);

    ResponseEntity<String> httpResp = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.GET,
            entity, String.class);
    String json = httpResp.getBody();
    LOGGER.info("JSON [{}]", json);
    LOGGER.info("STATUS [{}]", httpResp.getStatusCode().toString());

    Map<String, Object> map = new HashMap<>();
    ObjectMapper mapper = new ObjectMapper();

    map = mapper.readValue(json, new TypeReference<HashMap<String, Object>>() {
    });//w  w w  .  j  a v a 2  s.c  o  m
    return map;
}

From source file:com.ge.predix.test.utils.PrivilegeHelper.java

public BaseResource[] listResources(final RestTemplate restTemplate, final String acsEndpoint,
        final HttpHeaders headers) {
    URI uri = URI.create(acsEndpoint + ACS_RESOURCE_API_PATH);
    ResponseEntity<BaseResource[]> response = restTemplate.exchange(uri, HttpMethod.GET,
            new HttpEntity<>(headers), BaseResource[].class);
    return response.getBody();
}

From source file:uta.ak.TestNodejsInterface.java

private void testFromDB() throws Exception {

    Connection con = null; //MYSQL
    Class.forName("com.mysql.jdbc.Driver").newInstance(); //MYSQL
    con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/USTTMP", "root", "root.123"); //MYSQL
    System.out.println("connection yes");

    System.out.println("query records...");
    String querySQL = "SELECT" + "   * " + "FROM " + "   c_rawtext " + "WHERE " + "tag like 'function%'";

    PreparedStatement preparedStmt = con.prepareStatement(querySQL);
    ResultSet rs = preparedStmt.executeQuery();

    Set<String> filterDupSet = new HashSet<>();

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DATE, 1);//from w ww.j  ava2 s .  co  m
    SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    while (rs.next()) {

        System.out.println(rs.getString("title") + "  " + rs.getString("text") + "  " + rs.getString("tag"));

        String formattedDate = format1.format(new Date());

        String interfaceMsg = "<message> " + "    <title> " + rs.getString("title") + "    </title> "
                + "    <text> " + StringEscapeUtils.escapeXml10(rs.getString("text")) + "    </text> "
                + "    <textCreatetime> " + formattedDate + "    </textCreatetime> " + "    <tag> "
                + rs.getString("tag") + "    </tag> " + "</message>";

        //            String restUrl="http://192.168.0.103:8991/usttmp_textreceiver/rest/addText";
        String restUrl = "http://127.0.0.1:8991/usttmp_textreceiver/rest/addText";

        RestTemplate restTemplate = new RestTemplate();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.TEXT_XML);
        headers.setAccept(Arrays.asList(MediaType.TEXT_XML));
        //            headers.setContentLength();
        HttpEntity<String> entity = new HttpEntity<String>(interfaceMsg, headers);

        ResponseEntity<String> result = restTemplate.exchange(restUrl, HttpMethod.POST, entity, String.class);

        System.out.println(result.getBody());

    }

}

From source file:com.thecorpora.qbo.androidapk.rest.RESTClient.java

public void stopVideo(String url) {
    url = url.replace("stream", "stop");
    RestTemplate restTemplate = mRest.getRestTemplate();
    HttpHeaders httpHeaders = new HttpHeaders();
    HttpEntity<Object> requestEntity = new HttpEntity<Object>(httpHeaders);
    restTemplate.exchange(url, HttpMethod.POST, requestEntity, null);
}

From source file:org.intermine.app.net.request.JsonPostRequest.java

protected String post(String uriString, Map<String, ?> params, String obj) {
    RestTemplate rtp = getRestTemplate();
    HttpHeaders headers = getHeaders();/*from  www  .jav a  2 s .co  m*/

    HttpEntity<String> req;
    if (Strs.isNullOrEmpty(obj)) {
        req = new HttpEntity<>(headers);
    } else {
        req = new HttpEntity<>(obj, headers);
    }

    ResponseEntity<String> res;

    String uri = Uris.expandQuery(uriString, params);

    res = rtp.exchange(uri, POST, req, String.class);

    return res.getBody();
}

From source file:com.athena.dolly.controller.module.couchbase.CouchbaseClient.java

/**
 * <pre>//www .  j  a  v a2  s .c  o  m
 * API   .
 * </pre>
 * @param api
 * @param body
 * @param method
 * @return
 * @throws RestClientException
 * @throws Exception
 */
@SuppressWarnings("unchecked")
private Map<String, Object> submit(String api, String body, HttpMethod method)
        throws RestClientException, Exception {
    try {
        RestTemplate rt = new RestTemplate();
        ResponseEntity<?> response = rt.exchange(api, method, setHTTPEntity(body), Map.class);

        //logger.debug("[Request URL] : {}", api);
        //logger.debug("[Response] : {}", response);

        return (Map<String, Object>) response.getBody();
    } catch (RestClientException e) {
        logger.error("RestClientException has occurred.", e);
        throw e;
    } catch (Exception e) {
        logger.error("Unhandled Exception has occurred.", e);
        throw e;
    }
}

From source file:io.fabric8.che.starter.client.CheRestClient.java

public Workspace createWorkspace(String cheServerURL, String name, String stack, String repo, String branch)
        throws IOException {

    // The first step is to create the workspace
    String url = generateURL(cheServerURL, CheRestEndpoints.CREATE_WORKSPACE);
    String jsonTemplate = workspaceTemplate.createRequest().setName(name).setStack(stack)
            .setDescription(workspaceHelper.getDescription(repo, branch)).getJSON();

    RestTemplate template = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<String> entity = new HttpEntity<String>(jsonTemplate, headers);

    ResponseEntity<Workspace> workspaceResponse = template.exchange(url, HttpMethod.POST, entity,
            Workspace.class);
    Workspace workspace = workspaceResponse.getBody();

    LOG.info("Workspace has been created: {}", workspace);

    workspace.setName(workspace.getConfig().getName());
    workspace.setDescription(workspace.getConfig().getDescription());

    for (WorkspaceLink link : workspace.getLinks()) {
        if (WORKSPACE_LINK_IDE_URL.equals(link.getRel())) {
            workspace.setWorkspaceIdeUrl(link.getHref());
            break;
        }//  ww  w .j a v a2s  . c  o m
    }

    return workspace;
}