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:de.loercher.localpress.integration.GeoAndRatingITest.java

@Test
public void testAddArticle() {
    String nowString = "2015-10-12T08:00+02:00[Europe/Berlin]";
    ZonedDateTime now = new DateTimeConverter().fromString(nowString);

    AddArticleEntityDTO geoDTO = new AddArticleEntityDTO(nowString);
    Instant instant = now.toInstant();
    Instant fir = Instant.now();

    MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    headers.add("UserID", "ulf");

    HttpEntity<AddArticleEntityDTO> request = new HttpEntity<>(geoDTO, headers);

    RestTemplate template = new RestTemplate();
    ResponseEntity<Map> result = template.postForEntity("http://52.29.77.191:8080/localpress/feedback", request,
            Map.class);

    Instant afterRating = Instant.now();

    GeoBaseEntity.EntityBuilder builder = new GeoBaseEntity.EntityBuilder();
    GeoBaseEntity entity = builder.author("ulf")
            .coordinates(Arrays.asList(new Coordinate[] { new Coordinate(50.1, 8.4) }))
            .timestamp(now.toEpochSecond()).content("abc.de").title("mein titel").user("ulf").build();

    HttpEntity<GeoBaseEntity> second = new HttpEntity<>(entity, headers);
    System.out.println(result.getBody().get("articleID"));

    template.put("http://euve33985.vserver.de:8080/geo/" + result.getBody().get("articleID"), second);

    Instant afterGeoPut = Instant.now();

    result = template.getForEntity("http://euve33985.vserver.de:8080/geo/" + result.getBody().get("articleID"),
            Map.class);

    Instant afterGeoGet = Instant.now();

    assertEquals("User ID has changed over time!", "ulf", result.getBody().get("user"));
    assertEquals("Content URL has changed over time!", "abc.de", result.getBody().get("content"));

    DateTimeConverter conv = new DateTimeConverter();

    Duration first = Duration.between(fir, afterRating);
    Duration sec = Duration.between(afterRating, afterGeoPut);
    Duration third = Duration.between(afterGeoPut, afterGeoGet);

    System.out.println("Begin: " + conv.toString(now));
    System.out.println("Time until POST to rating: " + new Double(first.toMillis()) / 1000);
    System.out.println("Time until PUT to geo: " + new Double(sec.toMillis()) / 1000);
    System.out.println("Time until GET to geo: " + new Double(third.toMillis()) / 1000);
}

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

@Override
public SimpleReturnCode loadDataFromNetwork() throws Exception {
    MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
    params.set("uid", _uid);
    params.set("psw", _password);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    HttpEntity<MultiValueMap<String, String>> req = new HttpEntity<MultiValueMap<String, String>>(params,
            headers);//from ww w .  j  a va2  s .  c  om

    return getRestTemplate().postForObject(
            /* "http://rhymin.jnrain.com/api/login/", */
            "http://bbs.jnrain.com/rainstyle/apilogin.php", req, SimpleReturnCode.class);
}

From source file:org.n52.restfulwpsproxy.wps.GetStatusClient.java

public StatusInfoDocument getStatusInfo(String processId, String jobId) {
    HttpEntity<?> requestEntity = new HttpEntity<Object>(null, headers);

    ResponseEntity<StatusInfoDocument> statusInfo = restTemplate.exchange(
            new RequestUrlBuilder(GET_STATUS).jobID(jobId).build(), HttpMethod.GET, requestEntity,
            StatusInfoDocument.class);

    return statusInfo.getBody();
}

From source file:fi.helsinki.opintoni.integration.pagemetadata.SpringPageMetaDataHttpClient.java

@Override
public Optional<String> getPageBody(String pageUrl) {
    Optional<String> pageBody = Optional.empty();
    try {/*from w  w w.  j  a v  a2 s. c  om*/
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Lists.newArrayList(MediaType.TEXT_HTML));
        headers.add(USER_AGENT_KEY, USER_AGENT);
        HttpEntity<String> entity = new HttpEntity<>(PARAMETERS_KEY, headers);

        ResponseEntity<String> response = metaDataRestTemplate.exchange(pageUrl, HttpMethod.GET, entity,
                String.class);
        if (response.getStatusCode().equals(HttpStatus.OK)) {
            pageBody = Optional.ofNullable(response.getBody());
        }
    } catch (Exception e) {
    }

    return pageBody;

}

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

protected String post() {
    RestTemplate rtp = getRestTemplate();
    HttpHeaders headers = getHeaders();//w  w  w.  j  ava  2s. c  om
    String uriString = getUrl();
    Map<String, ?> params = getUrlParams();
    MultiValueMap<String, String> post = getPost();

    HttpEntity<?> req;
    if (null != post) {
        req = new HttpEntity<Object>(post, headers);
    } else {
        req = new HttpEntity<String>(headers);
    }

    ResponseEntity<String> res;

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

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

From source file:ai.emot.api.impl.EmotionTemplate.java

@Override
public EmotionProfile getFaceImageEmotionProfile(BufferedImage image) {

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.IMAGE_JPEG);
    HttpEntity<BufferedImage> entity = new HttpEntity<BufferedImage>(image, headers);

    ResponseEntity<EmotionProfile> response = restTemplate.exchange(apiBaseUrl + "/face/emotion",
            HttpMethod.POST, entity, EmotionProfile.class);
    return response.getBody();

}

From source file:org.schedoscope.metascope.controller.MetascopeAdminControllerTest.java

@Test
public void sometest() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.set("Referer", "/test");
    HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);

    ResponseEntity<String> response = this.restTemplate.exchange("/admin/sync", HttpMethod.POST, entity,
            String.class);
    assertEquals(302, response.getStatusCodeValue());
    assertTrue(response.getHeaders().get("Location").get(0).endsWith("/test"));
}

From source file:io.github.cdelmas.spike.springboot.hello.SampleController.java

@RequestMapping("/")
@ResponseBody/*ww w  .j  av  a  2 s.com*/
String home(@RequestHeader("Authorization") String authToken) {

    MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    headers.add("Accept", "application/json");
    headers.add("Authorization", authToken);
    HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(null, headers);

    RestTemplate rest = new RestTemplate();
    ResponseEntity<Car[]> responseEntity = rest.exchange("https://localhost:8443/cars", HttpMethod.GET,
            requestEntity, Car[].class);
    List<Car> cars = asList(responseEntity.getBody());

    return "Hello World! " + cars.stream().map(Car::getName).collect(toList());
}

From source file:net.orpiske.tcs.service.rest.functional.DomainCreateTest.java

@Test
public void testDomainCreation() {
    HttpEntity<Domain> requestEntity = new HttpEntity<Domain>(RestDataFixtures.customCsp(),
            getHeaders(USERNAME + ":" + GOOD_PASSWORD));

    RestTemplate template = new RestTemplate();
    ResponseEntity<Domain> responseEntity = template
            .postForEntity("http://localhost:8080/tcs/domain/terra.com.br", requestEntity, Domain.class);

    String path = responseEntity.getHeaders().getLocation().getPath();

    assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
    assertTrue("The returned path (" + path + ") does not match the expected one",
            path.startsWith("/tcs/domain/terra.com.br"));
}

From source file:org.messic.android.util.RestJSONClient.java

/**
 * Rest POST petition to the server at the url param, sending all the post parameters defiend at formData. This post
 * return an object (json marshalling) of class defined at clazz parameter. You should register a
 * {@link RestListener} in order to obtain the returned object, this is because the petition is done in an async
 * process./*w  w w .j a  v  a2s .  c om*/
 * 
 * @param url {@link string} URL to attack
 * @param formData {@link MultiValueMap}<?,?/> map of parameters to send
 * @param clazz Class<T/> class that you will marshall to a json object
 * @param rl {@link RestListener} listener to push the object returned
 */
public static <T> void post(final String url, MultiValueMap<?, ?> formData, final Class<T> clazz,
        final RestListener<T> rl) {
    final RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    // Sending multipart/form-data
    requestHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    // Populate the MultiValueMap being serialized and headers in an HttpEntity object to use for the request
    final HttpEntity<MultiValueMap<?, ?>> requestEntity = new HttpEntity<MultiValueMap<?, ?>>(formData,
            requestHeaders);

    AsyncTask<Void, Void, Void> at = new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            try {
                ResponseEntity<T> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, clazz);
                rl.response(response.getBody());
            } catch (Exception e) {
                rl.fail(e);
            }
            return null;
        }

    };

    at.execute();
}