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(MultiValueMap<String, String> headers) 

Source Link

Document

Create a new HttpEntity with the given headers and no body.

Usage

From source file:com.alcatel.hello.actuator.ui.SampleActuatorUIApplicationTests.java

@Test
public void testError() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
    ResponseEntity<String> entity = new TestRestTemplate().exchange("http://localhost:" + this.port + "/error",
            HttpMethod.GET, new HttpEntity<Void>(headers), String.class);

    assertEquals(HttpStatus.OK, entity.getStatusCode());
    assertTrue("Wrong body:\n" + entity.getBody(), entity.getBody().contains("<html>"));
    assertTrue("Wrong body:\n" + entity.getBody(), entity.getBody().contains("<body>"));
    assertTrue("Wrong body:\n" + entity.getBody(),
            entity.getBody().contains("Please contact the operator with the above information"));
}

From source file:com.tce.oauth2.spring.client.controller.OAuthController.java

@RequestMapping("/oauth2callback")
public String callback(@RequestParam("code") String authorizationCode, HttpServletRequest request) {

    // call OAuth Server with response code to get the access token
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(OAUTH_URL + "/oauth/token")
            .queryParam("grant_type", "authorization_code").queryParam("code", authorizationCode)
            .queryParam("redirect_uri", OAUTH_REDIRECT_URI);
    ResponseEntity<OAuthToken> response = restTemplate.exchange(builder.build().encode().toUri(),
            HttpMethod.POST, new HttpEntity<>(createHeaders(OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET)),
            OAuthToken.class);
    if (response.getStatusCode().is4xxClientError()) {
        return "redirect:/login";
    }//w  ww  .ja  v a  2s .c  om

    // get the access token
    OAuthToken oauthToken = response.getBody();
    // set access token to the session
    request.getSession().setAttribute("access_token", oauthToken.getAccessToken());
    // get the user information
    return "redirect:/userinfo";
}

From source file:com.acc.test.UserWebServiceTest.java

@Test()
public void testGetUserReviews_Success_JSON_Deep() {
    final HttpEntity<String> requestEntity = new HttpEntity<String>(getJSONHeaders());
    final ResponseEntity<ReviewDataList> response = template.exchange(
            "http://localhost:9001/rest/v1/users/{userid}/reviews", HttpMethod.GET, requestEntity,
            ReviewDataList.class, TestConstants.USERNAME);
    assertEquals("application/json;charset=UTF-8", response.getHeaders().getContentType().toString());

    final ReviewDataList reviews = response.getBody();
    assertEquals(5, reviews.getReviews().size());
}

From source file:org.slc.sli.dashboard.client.RESTClient.java

/**
 * Make a request to a REST service and convert the result to JSON
 * /*from   w  ww. j av  a  2  s. c om*/
 * @param path
 *            the unique portion of the requested REST service URL
 * @param token
 *            not used yet
 *
 * @param fullEntities 
 *             flag for returning expanded entities from the API
 *            
 * @return a {@link JsonElement} if the request is successful and returns valid JSON, otherwise
 *         null.
 * @throws NoSessionException
 */
public String makeJsonRequestWHeaders(String path, String token) {

    if (token != null) {

        URLBuilder url = null;
        if (!path.startsWith("http")) {
            url = new URLBuilder(getSecurityUrl());
            url.addPath(path);
        } else {
            url = new URLBuilder(path);
        }

        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Bearer " + token);
        HttpEntity entity = new HttpEntity(headers);
        logger.debug("Accessing API at: {}", url);
        HttpEntity<String> response = null;
        try {
            response = exchange(template, url.toString(), HttpMethod.GET, entity, String.class);
        } catch (HttpClientErrorException e) {
            logger.debug("Catch HttpClientException: {}", e.getStatusCode());
        }
        if (response == null) {
            return null;
        }
        return response.getBody();
    }
    logger.debug("Token is null in call to RESTClient for path {}", path);

    return null;
}

From source file:org.cloudfoundry.identity.uaa.login.feature.SamlLoginIT.java

@Test
public void testContentTypes() throws Exception {
    String loginUrl = baseUrl + "/login";

    HttpHeaders jsonHeaders = new HttpHeaders();
    jsonHeaders.add("Accept", "application/json");
    ResponseEntity<Map> jsonResponseEntity = restOperations.exchange(loginUrl, HttpMethod.GET,
            new HttpEntity<>(jsonHeaders), Map.class);
    assertThat(jsonResponseEntity.getHeaders().get("Content-Type").get(0),
            containsString(APPLICATION_JSON_VALUE));

    HttpHeaders htmlHeaders = new HttpHeaders();
    htmlHeaders.add("Accept", "text/html");
    ResponseEntity<Void> htmlResponseEntity = restOperations.exchange(loginUrl, HttpMethod.GET,
            new HttpEntity<>(htmlHeaders), Void.class);
    assertThat(htmlResponseEntity.getHeaders().get("Content-Type").get(0), containsString(TEXT_HTML_VALUE));

    HttpHeaders defaultHeaders = new HttpHeaders();
    defaultHeaders.add("Accept", "*/*");
    ResponseEntity<Void> defaultResponseEntity = restOperations.exchange(loginUrl, HttpMethod.GET,
            new HttpEntity<>(defaultHeaders), Void.class);
    assertThat(defaultResponseEntity.getHeaders().get("Content-Type").get(0), containsString(TEXT_HTML_VALUE));
}

From source file:sample.jetty.SampleJetty8ApplicationTests.java

@Test
public void testHomeBasicAuthWrongCredentials403() throws Exception {
    ResponseEntity<String> entity = new TestRestTemplate().exchange(
            "http://localhost:" + this.port + "/static.html", HttpMethod.GET,
            new HttpEntity<String>(createHeaders("admin", "wrong-password")), String.class);
    assertEquals(HttpStatus.UNAUTHORIZED, entity.getStatusCode());
}

From source file:org.energyos.espi.thirdparty.web.custodian.AdministratorController.java

@RequestMapping(value = Routes.ROOT_SERVICE_STATUS, method = RequestMethod.GET)
public String showServiceStatus(ModelMap model) {

    ApplicationInformation applicationInformation = resourceService.findById(1L, ApplicationInformation.class);
    String statusUri = applicationInformation.getAuthorizationServerAuthorizationEndpoint()
            + "/ReadServiceStatus";
    // not sure this will work w/o the right seed information
    ////from   w w w .j  ava 2s. co  m
    Authorization authorization = resourceService.findByResourceUri(statusUri, Authorization.class);
    RetailCustomer retailCustomer = authorization.getRetailCustomer();

    String accessToken = authorization.getAccessToken();
    String serviceStatus = "OK";

    try {

        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.set("Authorization", "Bearer " + accessToken);
        @SuppressWarnings({ "unchecked", "rawtypes" })
        HttpEntity<?> requestEntity = new HttpEntity(requestHeaders);

        // get the subscription
        HttpEntity<String> httpResult = restTemplate.exchange(statusUri, HttpMethod.GET, requestEntity,
                String.class);

        // import it into the repository
        ByteArrayInputStream bs = new ByteArrayInputStream(httpResult.getBody().toString().getBytes());

        importService.importData(bs, retailCustomer.getId());

        List<EntryType> entries = importService.getEntries();

        // TODO: Use-Case 1 registration - service status

    } catch (Exception e) {
        // nothing there, so log the fact and move on. It will
        // get imported later.
        e.printStackTrace();
    }
    model.put("serviceStatus", serviceStatus);

    return "/custodian/datacustodian/showservicestatus";
}

From source file:com.auditbucket.client.AbRestClient.java

public String ping() {
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
    HttpHeaders httpHeaders = getHeaders(userName, password);
    HttpEntity requestEntity = new HttpEntity<>(httpHeaders);
    try {//from   w ww .  java  2s . c  o  m
        ResponseEntity<String> response = restTemplate.exchange(PING, HttpMethod.GET, requestEntity,
                String.class);
        return response.getBody();
    } catch (HttpClientErrorException e) {
        // ToDo: Rest error handling pretty useless. need to know why it's failing
        logger.error("AB Client Audit error {}", getErrorMessage(e));
        return "err";
    } catch (HttpServerErrorException e) {
        logger.error("AB Server Audit error {}", getErrorMessage(e));
        return "err";

    }

}

From source file:net.orpiske.tcs.client.services.TagCloudServiceClient.java

@Override
public TagCloud requestTagCloud() {

    ResponseEntity<TagCloud> responseEntity = restTemplate.exchange(endPoint.getTagCloudServiceLocation(),
            HttpMethod.GET, new HttpEntity<Object>(getHeaders()), TagCloud.class);

    TagCloud tagCloud = responseEntity.getBody();

    return tagCloud;
}

From source file:com.iata.ndc.trial.controllers.DefaultController.java

@RequestMapping(value = "/ba", method = RequestMethod.GET)
public String getCal() {

    RestTemplate restTemplate = new RestTemplate();
    List<HttpMessageConverter<?>> converters = new ArrayList<>();
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.getObjectMapper().configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
    converters.add(converter);/*from  w  w w . j a  va 2 s  .co  m*/
    restTemplate.setMessageConverters(converters);

    HttpHeaders headers = new HttpHeaders();
    headers.add("client-key", "zmd9apqgg2jwekf8zgqg5ybf");
    headers.setContentType(MediaType.APPLICATION_JSON);

    ResponseEntity<BALocationsResponseWrapper> baLocationsResponse = restTemplate.exchange(
            "https://api.ba.com/rest-v1/v1/balocations", HttpMethod.GET, new HttpEntity<Object>(headers),
            BALocationsResponseWrapper.class);
    System.out.println(baLocationsResponse.getBody().getGetBALocationsResponse().getCountry().size());
    return "index";
}