Example usage for org.springframework.http HttpEntity HttpEntity

List of usage examples for org.springframework.http HttpEntity HttpEntity

Introduction

In this page you can find the example usage for org.springframework.http HttpEntity HttpEntity.

Prototype

public HttpEntity(@Nullable T body, @Nullable MultiValueMap<String, String> headers) 

Source Link

Document

Create a new HttpEntity with the given body and headers.

Usage

From source file:org.awesomeagile.integrations.hackpad.RestTemplateHackpadClient.java

@Override
public void updateHackpad(PadIdentity padIdentity, String content) {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.TEXT_HTML);
    HttpEntity<String> updateEntity = new HttpEntity<>(content, headers);
    HackpadStatus status = restTemplate.postForObject(fullUrl(UPDATE_URL), updateEntity, HackpadStatus.class,
            ImmutableMap.of("padId", padIdentity.getPadId()));
    if (!status.isSuccess()) {
        throw new RuntimeException("Failure to update a Hackpad.");
    }//from w w  w .  j av  a  2  s .  c  om
}

From source file:com.salmon.security.xacml.demo.springmvc.rest.HTTPPopulatorsTest.java

@Test
public void badUserPrevented() {
    HttpHeaders headers = this.getHeaders("wrongusername" + ":" + "wrongpwd");

    RestTemplate template = new RestTemplate();

    HttpEntity<String> requestEntity = new HttpEntity<String>(DriverFixtures.standardDriverJSON(), headers);

    try {/*from w w  w .  j a v  a2 s  .c om*/
        ResponseEntity<Driver> entity = template.postForEntity(
                "http://localhost:8085/xacml/populators/dvla/driveradd", requestEntity, Driver.class);
        fail("Request Passed incorrectly with status " + entity.getStatusCode());
    } catch (HttpClientErrorException ex) {
        assertEquals(HttpStatus.UNAUTHORIZED, ex.getStatusCode());
    }

}

From source file:org.cloudfoundry.identity.api.web.CloudfoundryApiIntegrationTests.java

@Test
public void testClientAccessesProtectedResource() throws Exception {
    OAuth2AccessToken accessToken = context.getAccessToken();
    // add an approval for the scope requested
    HttpHeaders approvalHeaders = new HttpHeaders();
    approvalHeaders.set("Authorization", "bearer " + accessToken.getValue());
    Date oneMinuteAgo = new Date(System.currentTimeMillis() - 60000);
    Date expiresAt = new Date(System.currentTimeMillis() + 60000);
    ResponseEntity<Approval[]> approvals = serverRunning.getRestTemplate().exchange(
            serverRunning.getUrl("/uaa/approvals"), HttpMethod.PUT,
            new HttpEntity<Approval[]>((new Approval[] {
                    new Approval(testAccounts.getUserName(), "app", "cloud_controller.read", expiresAt,
                            ApprovalStatus.APPROVED, oneMinuteAgo),
                    new Approval(testAccounts.getUserName(), "app", "openid", expiresAt,
                            ApprovalStatus.APPROVED, oneMinuteAgo),
                    new Approval(testAccounts.getUserName(), "app", "password.write", expiresAt,
                            ApprovalStatus.APPROVED, oneMinuteAgo) }),
                    approvalHeaders),//from   w  ww .j  av a2s  .  c  om
            Approval[].class);
    assertEquals(HttpStatus.OK, approvals.getStatusCode());

    // System.err.println(accessToken);
    // The client doesn't know how to use an OAuth bearer token
    CloudFoundryClient client = new CloudFoundryClient("Bearer " + accessToken.getValue(),
            testAccounts.getCloudControllerUrl());
    CloudInfo info = client.getCloudInfo();
    assertNotNull("Wrong cloud info: " + info.getDescription(), info.getUser());
}

From source file:org.jnrain.mobile.accounts.kbs.KBSRegisterRequest.java

@Override
public KBSRegisterResult loadDataFromNetwork() throws Exception {
    MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();

    if (isPreflight) {
        // preflight request, only prereg flag is sent
        params.set("prereg", "1");
    } else {/*from   w  w w .  j  a va2  s .  c om*/
        // please keep this in sync with rainstyle/apiregister.php
        params.set("userid", _uid);
        params.set("password", _password);
        params.set("nickname", _nickname);
        params.set("realname", _realname);
        params.set("email", _email);
        params.set("phone", _phone);
        params.set("idnumber", _idnumber);
        params.set("gender", Integer.toString(_gender));
        params.set("captcha", _captcha);
    }

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    HttpEntity<MultiValueMap<String, String>> req = new HttpEntity<MultiValueMap<String, String>>(params,
            headers);

    return getRestTemplate().postForObject("http://bbs.jnrain.com/rainstyle/apiregister.php", req,
            KBSRegisterResult.class);
}

From source file:org.cloudfoundry.identity.api.web.AppsIntegrationTests.java

/**
 * tests a happy-day flow of the native application profile.
 *//*w ww. ja  v a 2  s.  c  o m*/
@Test
public void testHappyDay() throws Exception {

    RestOperations restTemplate = serverRunning.createRestTemplate();
    ResponseEntity<String> response = restTemplate.getForEntity(serverRunning.getUrl("/api/apps"),
            String.class);
    // first make sure the resource is actually protected.
    assertNotSame(HttpStatus.OK, response.getStatusCode());
    HttpHeaders approvalHeaders = new HttpHeaders();
    OAuth2AccessToken accessToken = context.getAccessToken();
    approvalHeaders.set("Authorization", "bearer " + accessToken.getValue());
    Date oneMinuteAgo = new Date(System.currentTimeMillis() - 60000);
    Date expiresAt = new Date(System.currentTimeMillis() + 60000);
    ResponseEntity<Approval[]> approvals = serverRunning.getRestTemplate().exchange(
            serverRunning.getUrl("/uaa/approvals"), HttpMethod.PUT,
            new HttpEntity<Approval[]>((new Approval[] {
                    new Approval(testAccounts.getUserName(), "app", "cloud_controller.read", expiresAt,
                            ApprovalStatus.APPROVED, oneMinuteAgo),
                    new Approval(testAccounts.getUserName(), "app", "openid", expiresAt,
                            ApprovalStatus.APPROVED, oneMinuteAgo),
                    new Approval(testAccounts.getUserName(), "app", "password.write", expiresAt,
                            ApprovalStatus.APPROVED, oneMinuteAgo) }),
                    approvalHeaders),
            Approval[].class);
    assertEquals(HttpStatus.OK, approvals.getStatusCode());

    ResponseEntity<String> result = serverRunning.getForString("/api/apps");
    assertEquals(HttpStatus.OK, result.getStatusCode());
    String body = result.getBody();
    assertTrue("Wrong response: " + body, body.contains("dsyerapi.cloudfoundry.com"));

}

From source file:khs.trouble.service.impl.TroubleService.java

public String kill(String serviceName, String instanceId, String ltoken) {
    if (token != ltoken) {
        throw new RuntimeException("Invalid Access Token");
    }/*from  w  w  w .  j  a  v a  2  s  .  c  o m*/

    String url = FormatUrl.url(serviceInstanceURL(serviceName, instanceId) + "trouble/kill", ssl);

    // invoke kill api...
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.TEXT_PLAIN));
    headers.add("token", token);
    HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);

    try {
        // int instanceCount = registry.instanceCount(serviceName);
        ResponseEntity<String> result = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
        if (result.getStatusCode() == HttpStatus.OK) {
            eventService.killed(serviceName, url);
            // monitorServiceRecovery(serviceName, instanceCount);
        }
    } catch (Exception e) {
        eventService.attempted("Attempted to Kill service " + serviceName + " at " + url
                + " Failed due to exception " + e.getMessage());
    }
    return serviceName;
}

From source file:com.logaritex.hadoop.configuration.manager.http.AndroidHttpService.java

public <R> R post(String url, Object request, Class<R> responseType, Object... uriVariables) {

    R response = restTemplate.exchange(baseUrl + url, HttpMethod.POST,
            new HttpEntity<Object>(request, httpHeaders), responseType, uriVariables).getBody();

    return response;
}

From source file:fi.helsinki.opintoni.integration.unisport.UnisportRestClient.java

private HttpEntity<String> getAuthorizationHeader(final Long unisportUserId) {
    HttpHeaders headers = new HttpHeaders();
    headers.add(AUTHORIZATION_HEADER, unisportJWTService.generateToken(unisportUserId));
    return new HttpEntity<>("parameters", headers);
}

From source file:de.codecentric.boot.admin.services.ApplicationRegistratorTest.java

@SuppressWarnings("rawtypes")
@Test//from w  ww .j  av a  2  s  .c o  m
public void register_successful() {
    when(restTemplate.postForEntity(isA(String.class), isA(HttpEntity.class), eq(Map.class)))
            .thenReturn(new ResponseEntity<Map>(Collections.singletonMap("id", "-id-"), HttpStatus.CREATED));

    assertTrue(registrator.register());
    verify(restTemplate).postForEntity("http://sba:8080/api/applications",
            new HttpEntity<>(Application.create("AppName").withHealthUrl("http://localhost:8080/health")
                    .withManagementUrl("http://localhost:8080/mgmt").withServiceUrl("http://localhost:8080")
                    .build(), headers),
            Map.class);
}

From source file:com.bradley.musicapp.test.restapi.TrackRestControllerTest.java

@Test
public void testTrackUpdate() {
    ctx = new AnnotationConfigApplicationContext(ConnectionConfigTest.class);
    trackService = ctx.getBean(TrackFindService.class);
    // LEFT AS AN EXERCISE FOR YOU
    // GET THE TRACK and THEN CHANGE AND MAKE A COPY
    //THEN SEND TO THE SERVER USING A PUT OR POST
    // THEN READ BACK TO SEE IF YOUR CHANGE HAS HAPPENED
    System.out.println("id = " + id);
    System.out.println("track = " + trackService);
    Track foundTrack = trackService.find(id);
    Track track = new Track.Builder().track(foundTrack).trackName("lollipop").trackLength("02:22").build();

    HttpEntity<Track> requestEntity = new HttpEntity<>(track, getContentType());
    //        Make the HTTP POST request, marshaling the request to JSON, and the response to a String
    ResponseEntity<String> responseEntity = restTemplate.exchange(URL + "api/track/update", HttpMethod.PUT,
            requestEntity, String.class);
    System.out.println(" THE RESPONSE BODY " + responseEntity.getBody());
    System.out.println(" THE RESPONSE STATUS CODE " + responseEntity.getStatusCode());
    System.out.println(" THE RESPONSE IS HEADERS " + responseEntity.getHeaders());

    Track foundTrack1 = trackService.find(id);
    System.out.println("updated track = " + track + " | original track = " + foundTrack1);
    Assert.assertEquals(responseEntity.getStatusCode(), HttpStatus.OK);

}