Search in sources :

Example 36 with HttpEntity

use of org.springframework.http.HttpEntity in project spring-framework by spring-projects.

the class RestTemplateTests method postForLocationEntityContentType.

@Test
public void postForLocationEntityContentType() throws Exception {
    given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(request);
    String helloWorld = "Hello World";
    MediaType contentType = MediaType.TEXT_PLAIN;
    given(converter.canWrite(String.class, contentType)).willReturn(true);
    HttpHeaders requestHeaders = new HttpHeaders();
    given(request.getHeaders()).willReturn(requestHeaders);
    converter.write(helloWorld, contentType, request);
    given(request.execute()).willReturn(response);
    given(errorHandler.hasError(response)).willReturn(false);
    HttpHeaders responseHeaders = new HttpHeaders();
    URI expected = new URI("http://example.com/hotels");
    responseHeaders.setLocation(expected);
    given(response.getHeaders()).willReturn(responseHeaders);
    HttpStatus status = HttpStatus.OK;
    given(response.getStatusCode()).willReturn(status);
    given(response.getStatusText()).willReturn(status.getReasonPhrase());
    HttpHeaders entityHeaders = new HttpHeaders();
    entityHeaders.setContentType(contentType);
    HttpEntity<String> entity = new HttpEntity<>(helloWorld, entityHeaders);
    URI result = template.postForLocation("http://example.com", entity);
    assertEquals("Invalid POST result", expected, result);
    verify(response).close();
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) HttpEntity(org.springframework.http.HttpEntity) HttpStatus(org.springframework.http.HttpStatus) MediaType(org.springframework.http.MediaType) URI(java.net.URI) Test(org.junit.Test)

Example 37 with HttpEntity

use of org.springframework.http.HttpEntity in project spring-framework by spring-projects.

the class RestTemplateTests method exchangeParameterizedType.

@Test
@SuppressWarnings("rawtypes")
public void exchangeParameterizedType() throws Exception {
    GenericHttpMessageConverter converter = mock(GenericHttpMessageConverter.class);
    template.setMessageConverters(Collections.<HttpMessageConverter<?>>singletonList(converter));
    ParameterizedTypeReference<List<Integer>> intList = new ParameterizedTypeReference<List<Integer>>() {
    };
    given(converter.canRead(intList.getType(), null, null)).willReturn(true);
    given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
    given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(this.request);
    HttpHeaders requestHeaders = new HttpHeaders();
    given(this.request.getHeaders()).willReturn(requestHeaders);
    given(converter.canWrite(String.class, String.class, null)).willReturn(true);
    String requestBody = "Hello World";
    converter.write(requestBody, String.class, null, this.request);
    given(this.request.execute()).willReturn(response);
    given(errorHandler.hasError(response)).willReturn(false);
    List<Integer> expected = Collections.singletonList(42);
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.setContentType(MediaType.TEXT_PLAIN);
    responseHeaders.setContentLength(10);
    given(response.getStatusCode()).willReturn(HttpStatus.OK);
    given(response.getHeaders()).willReturn(responseHeaders);
    given(response.getBody()).willReturn(new ByteArrayInputStream(Integer.toString(42).getBytes()));
    given(converter.canRead(intList.getType(), null, MediaType.TEXT_PLAIN)).willReturn(true);
    given(converter.read(eq(intList.getType()), eq(null), any(HttpInputMessage.class))).willReturn(expected);
    given(response.getStatusCode()).willReturn(HttpStatus.OK);
    HttpStatus status = HttpStatus.OK;
    given(response.getStatusCode()).willReturn(status);
    given(response.getStatusText()).willReturn(status.getReasonPhrase());
    HttpHeaders entityHeaders = new HttpHeaders();
    entityHeaders.set("MyHeader", "MyValue");
    HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, entityHeaders);
    ResponseEntity<List<Integer>> result = template.exchange("http://example.com", HttpMethod.POST, requestEntity, intList);
    assertEquals("Invalid POST result", expected, result.getBody());
    assertEquals("Invalid Content-Type", MediaType.TEXT_PLAIN, result.getHeaders().getContentType());
    assertEquals("Invalid Accept header", MediaType.TEXT_PLAIN_VALUE, requestHeaders.getFirst("Accept"));
    assertEquals("Invalid custom header", "MyValue", requestHeaders.getFirst("MyHeader"));
    assertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode());
    verify(response).close();
}
Also used : HttpInputMessage(org.springframework.http.HttpInputMessage) HttpHeaders(org.springframework.http.HttpHeaders) HttpEntity(org.springframework.http.HttpEntity) HttpStatus(org.springframework.http.HttpStatus) URI(java.net.URI) ByteArrayInputStream(java.io.ByteArrayInputStream) ParameterizedTypeReference(org.springframework.core.ParameterizedTypeReference) List(java.util.List) GenericHttpMessageConverter(org.springframework.http.converter.GenericHttpMessageConverter) Test(org.junit.Test)

Example 38 with HttpEntity

use of org.springframework.http.HttpEntity in project spring-framework by spring-projects.

the class ResponseEntityResultHandler method handleResult.

@Override
public Mono<Void> handleResult(ServerWebExchange exchange, HandlerResult result) {
    Mono<?> returnValueMono;
    MethodParameter bodyParameter;
    ReactiveAdapter adapter = getAdapter(result);
    if (adapter != null) {
        Assert.isTrue(!adapter.isMultiValue(), "Only a single ResponseEntity supported");
        returnValueMono = Mono.from(adapter.toPublisher(result.getReturnValue()));
        bodyParameter = result.getReturnTypeSource().nested().nested();
    } else {
        returnValueMono = Mono.justOrEmpty(result.getReturnValue());
        bodyParameter = result.getReturnTypeSource().nested();
    }
    return returnValueMono.then(returnValue -> {
        Assert.isInstanceOf(HttpEntity.class, returnValue, "HttpEntity expected");
        HttpEntity<?> httpEntity = (HttpEntity<?>) returnValue;
        if (httpEntity instanceof ResponseEntity) {
            ResponseEntity<?> responseEntity = (ResponseEntity<?>) httpEntity;
            exchange.getResponse().setStatusCode(responseEntity.getStatusCode());
        }
        HttpHeaders entityHeaders = httpEntity.getHeaders();
        HttpHeaders responseHeaders = exchange.getResponse().getHeaders();
        if (!entityHeaders.isEmpty()) {
            entityHeaders.entrySet().stream().filter(entry -> !responseHeaders.containsKey(entry.getKey())).forEach(entry -> responseHeaders.put(entry.getKey(), entry.getValue()));
        }
        if (httpEntity.getBody() == null) {
            return exchange.getResponse().setComplete();
        }
        String etag = entityHeaders.getETag();
        Instant lastModified = Instant.ofEpochMilli(entityHeaders.getLastModified());
        HttpMethod httpMethod = exchange.getRequest().getMethod();
        if (SAFE_METHODS.contains(httpMethod) && exchange.checkNotModified(etag, lastModified)) {
            return exchange.getResponse().setComplete();
        }
        return writeBody(httpEntity.getBody(), bodyParameter, exchange);
    });
}
Also used : RequestEntity(org.springframework.http.RequestEntity) Arrays(java.util.Arrays) ReactiveAdapter(org.springframework.core.ReactiveAdapter) RequestedContentTypeResolver(org.springframework.web.reactive.accept.RequestedContentTypeResolver) HttpHeaders(org.springframework.http.HttpHeaders) HttpMethod(org.springframework.http.HttpMethod) Mono(reactor.core.publisher.Mono) Instant(java.time.Instant) HandlerResult(org.springframework.web.reactive.HandlerResult) ServerWebExchange(org.springframework.web.server.ServerWebExchange) List(java.util.List) HttpEntity(org.springframework.http.HttpEntity) MethodParameter(org.springframework.core.MethodParameter) HandlerResultHandler(org.springframework.web.reactive.HandlerResultHandler) ResponseEntity(org.springframework.http.ResponseEntity) ResolvableType(org.springframework.core.ResolvableType) ReactiveAdapterRegistry(org.springframework.core.ReactiveAdapterRegistry) HttpMessageWriter(org.springframework.http.codec.HttpMessageWriter) Assert(org.springframework.util.Assert) HttpHeaders(org.springframework.http.HttpHeaders) ResponseEntity(org.springframework.http.ResponseEntity) HttpEntity(org.springframework.http.HttpEntity) Instant(java.time.Instant) MethodParameter(org.springframework.core.MethodParameter) ReactiveAdapter(org.springframework.core.ReactiveAdapter) HttpMethod(org.springframework.http.HttpMethod)

Example 39 with HttpEntity

use of org.springframework.http.HttpEntity in project dhis2-core by dhis2.

the class DefaultSynchronizationManager method getBasicAuthRequestEntity.

/**
     * Creates an HTTP entity for requests with appropriate header for basic
     * authentication.
     */
private <T> HttpEntity<T> getBasicAuthRequestEntity(String username, String password) {
    HttpHeaders headers = new HttpHeaders();
    headers.set(HEADER_AUTHORIZATION, CodecUtils.getBasicAuthString(username, password));
    return new HttpEntity<>(headers);
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) HttpEntity(org.springframework.http.HttpEntity)

Example 40 with HttpEntity

use of org.springframework.http.HttpEntity in project geode by apache.

the class SimpleHttpRequester method getRequestEntity.

protected HttpEntity<?> getRequestEntity() {
    HttpHeaders requestHeaders = new HttpHeaders();
    if (this.securityProperties != null) {
        requestHeaders.setAll(securityProperties);
    }
    HttpEntity<?> requestEntity = new HttpEntity(requestHeaders);
    return requestEntity;
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) HttpEntity(org.springframework.http.HttpEntity)

Aggregations

HttpEntity (org.springframework.http.HttpEntity)104 HttpHeaders (org.springframework.http.HttpHeaders)81 Test (org.junit.Test)46 RestTemplate (org.springframework.web.client.RestTemplate)17 URI (java.net.URI)15 ArrayList (java.util.ArrayList)13 ResponseEntity (org.springframework.http.ResponseEntity)12 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)12 Map (java.util.Map)11 MediaType (org.springframework.http.MediaType)11 HashMap (java.util.HashMap)10 List (java.util.List)10 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)10 MultiValueMap (org.springframework.util.MultiValueMap)9 ByteArrayInputStream (java.io.ByteArrayInputStream)7 ByteArrayHttpMessageConverter (org.springframework.http.converter.ByteArrayHttpMessageConverter)7 MappingJackson2HttpMessageConverter (org.springframework.http.converter.json.MappingJackson2HttpMessageConverter)7 HttpStatus (org.springframework.http.HttpStatus)6 HttpMessageConverter (org.springframework.http.converter.HttpMessageConverter)6 StringHttpMessageConverter (org.springframework.http.converter.StringHttpMessageConverter)6