@Override public <T> RequestEntity<T> body(T body, Type type) { return new RequestEntity<>(body, this.headers, this.method, this.url, type); } }
@Test public void methods() throws URISyntaxException { URI url = new URI("http://example.com"); RequestEntity<?> entity = RequestEntity.get(url).build(); assertEquals(HttpMethod.GET, entity.getMethod()); entity = RequestEntity.post(url).build(); assertEquals(HttpMethod.POST, entity.getMethod()); entity = RequestEntity.head(url).build(); assertEquals(HttpMethod.HEAD, entity.getMethod()); entity = RequestEntity.options(url).build(); assertEquals(HttpMethod.OPTIONS, entity.getMethod()); entity = RequestEntity.put(url).build(); assertEquals(HttpMethod.PUT, entity.getMethod()); entity = RequestEntity.patch(url).build(); assertEquals(HttpMethod.PATCH, entity.getMethod()); entity = RequestEntity.delete(url).build(); assertEquals(HttpMethod.DELETE, entity.getMethod()); }
@Override public String toString() { StringBuilder builder = new StringBuilder("<"); builder.append(getMethod()); builder.append(' '); builder.append(getUrl()); builder.append(','); T body = getBody(); HttpHeaders headers = getHeaders(); if (body != null) { builder.append(body); builder.append(','); } builder.append(headers); builder.append('>'); return builder.toString(); }
@Override public boolean equals(@Nullable Object other) { if (this == other) { return true; } if (!super.equals(other)) { return false; } RequestEntity<?> otherEntity = (RequestEntity<?>) other; return (ObjectUtils.nullSafeEquals(getMethod(), otherEntity.getMethod()) && ObjectUtils.nullSafeEquals(getUrl(), otherEntity.getUrl())); }
@SuppressWarnings({ "rawtypes", "unchecked" }) private RequestEntity<?> createRequestEntityWithRootAppliedUri( RequestEntity<?> requestEntity) { return new RequestEntity(requestEntity.getBody(), requestEntity.getHeaders(), requestEntity.getMethod(), applyRootUriIfNecessary(requestEntity.getUrl()), requestEntity.getType()); }
@Test public void requestEntity() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.TEXT_PLAIN); String body = "foo"; HttpEntity<String> httpEntity = new HttpEntity<>(body, headers); RequestEntity<String> requestEntity = new RequestEntity<>(body, headers, HttpMethod.GET, new URI("/")); RequestEntity<String> requestEntity2 = new RequestEntity<>(body, headers, HttpMethod.GET, new URI("/")); assertEquals(body, requestEntity.getBody()); assertEquals(MediaType.TEXT_PLAIN, requestEntity.getHeaders().getContentType()); assertEquals("text/plain", requestEntity.getHeaders().getFirst("Content-Type")); assertEquals("text/plain", requestEntity.getHeaders().getFirst("Content-Type")); assertFalse(httpEntity.equals(requestEntity)); assertFalse(requestEntity.equals(httpEntity)); assertTrue(requestEntity.equals(requestEntity2)); assertTrue(requestEntity2.equals(requestEntity)); }
private static Map<String, Object> getOpenidConfiguration(String issuer) { ParameterizedTypeReference<Map<String, Object>> typeReference = new ParameterizedTypeReference<Map<String, Object>>() {}; RestTemplate rest = new RestTemplate(); try { URI uri = UriComponentsBuilder.fromUriString(issuer + "/.well-known/openid-configuration") .build() .toUri(); RequestEntity<Void> request = RequestEntity.get(uri).build(); return rest.exchange(request, typeReference).getBody(); } catch(RuntimeException e) { throw new IllegalArgumentException("Unable to resolve the OpenID Configuration with the provided Issuer of " + "\"" + issuer + "\"", e); } }
@Test public void get() { RequestEntity<Void> requestEntity = RequestEntity.get(URI.create("http://example.com")).accept( MediaType.IMAGE_GIF, MediaType.IMAGE_JPEG, MediaType.IMAGE_PNG).build(); assertNotNull(requestEntity); assertEquals(HttpMethod.GET, requestEntity.getMethod()); assertTrue(requestEntity.getHeaders().containsKey("Accept")); assertEquals("image/gif, image/jpeg, image/png", requestEntity.getHeaders().getFirst("Accept")); assertNull(requestEntity.getBody()); }
@Test public void normal() throws URISyntaxException { String headerName = "My-Custom-Header"; String headerValue = "HeaderValue"; URI url = new URI("http://example.com"); Integer entity = 42; RequestEntity<Object> requestEntity = RequestEntity.method(HttpMethod.GET, url) .header(headerName, headerValue).body(entity); assertNotNull(requestEntity); assertEquals(HttpMethod.GET, requestEntity.getMethod()); assertTrue(requestEntity.getHeaders().containsKey(headerName)); assertEquals(headerValue, requestEntity.getHeaders().getFirst(headerName)); assertEquals(entity, requestEntity.getBody()); }
@Test public void checkUri() throws Exception { URI url = new URI("http://localhost:" + port + "/foo?param=bar"); RequestEntity<Void> request = RequestEntity.post(url).build(); ResponseEntity<Void> response = new RestTemplate().exchange(request, Void.class); assertEquals(HttpStatus.OK, response.getStatusCode()); }
@Test public void shouldResolveRequestEntityArgument() throws Exception { String body = "Foo"; MediaType contentType = TEXT_PLAIN; servletRequest.addHeader("Content-Type", contentType.toString()); servletRequest.setMethod("GET"); servletRequest.setServerName("www.example.com"); servletRequest.setServerPort(80); servletRequest.setRequestURI("/path"); servletRequest.setContent(body.getBytes(StandardCharsets.UTF_8)); given(stringHttpMessageConverter.canRead(String.class, contentType)).willReturn(true); given(stringHttpMessageConverter.read(eq(String.class), isA(HttpInputMessage.class))).willReturn(body); Object result = processor.resolveArgument(paramRequestEntity, mavContainer, webRequest, null); assertTrue(result instanceof RequestEntity); assertFalse("The requestHandled flag shouldn't change", mavContainer.isRequestHandled()); RequestEntity<?> requestEntity = (RequestEntity<?>) result; assertEquals("Invalid method", HttpMethod.GET, requestEntity.getMethod()); // using default port (which is 80), so do not need to append the port (-1 means ignore) URI uri = new URI("http", null, "www.example.com", -1, "/path", null, null); assertEquals("Invalid url", uri, requestEntity.getUrl()); assertEquals("Invalid argument", body, requestEntity.getBody()); }
@Test public void uriVariablesExpansion() throws URISyntaxException { URI uri = new UriTemplate("http://example.com/{foo}").expand("bar"); RequestEntity.get(uri).accept(MediaType.TEXT_PLAIN).build(); String url = "http://www.{host}.com/{path}"; String host = "example"; String path = "foo/bar"; URI expected = new URI("http://www.example.com/foo/bar"); uri = new UriTemplate(url).expand(host, path); RequestEntity<?> entity = RequestEntity.get(uri).build(); assertEquals(expected, entity.getUrl()); Map<String, String> uriVariables = new HashMap<>(2); uriVariables.put("host", host); uriVariables.put("path", path); uri = new UriTemplate(url).expand(uriVariables); entity = RequestEntity.get(uri).build(); assertEquals(expected, entity.getUrl()); }
@SuppressWarnings("unchecked") @Test public void convertWhenAuthenticationMethodHeaderThenGetRequest() { ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build(); OAuth2UserRequest userRequest = new OAuth2UserRequest( clientRegistration, this.createAccessToken()); RequestEntity<?> requestEntity = this.converter.convert(userRequest); assertThat(requestEntity.getMethod()).isEqualTo(HttpMethod.GET); assertThat(requestEntity.getUrl().toASCIIString()).isEqualTo( clientRegistration.getProviderDetails().getUserInfoEndpoint().getUri()); HttpHeaders headers = requestEntity.getHeaders(); assertThat(headers.getAccept()).contains(MediaType.APPLICATION_JSON); assertThat(headers.getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo( "Bearer " + userRequest.getAccessToken().getTokenValue()); }
/** * Return the type of the request's body. * @return the request's body type, or {@code null} if not known * @since 4.3 */ @Nullable public Type getType() { if (this.type == null) { T body = getBody(); if (body != null) { return body.getClass(); } } return this.type; }
/** * Builds a {@link ParameterSet} from a {@link RequestEntity}. Currently only supports * JSON payload, and only basic JSON objects that are essentially key-value pairs, where the * values are primitives (String, numeric or boolean). * @param entity The RequestEntity payload, expected to be JSON. * @return a {@link ParameterSet} instance with key-value pairs from the JSON entity, or * and empty instance if there is no body in the entity. */ protected final ParameterSet getParamsFromEntity(RequestEntity<String> entity) { // attempt to build a parameter map from the request entity/payload if (entity != null && entity.hasBody()) { MediaType contentType = entity.getHeaders().getContentType(); String body = entity.getBody(); if (MediaType.APPLICATION_JSON.isCompatibleWith(contentType)) { // parse just a basic key-value styled JSON payload return handleJsonPayload(body); } else if (contentType.getSubtype().equals("xml")) { // handle XML payload return handleXmlPayload(body); } else { getLogger().error("RequestEntity does not have a JSON or XML payload. MediaType: " + contentType); } } return ParameterSetFactory.buildEmptyParameterSet(); }
@Test // SPR-13154 public void types() throws URISyntaxException { URI url = new URI("http://example.com"); List<String> body = Arrays.asList("foo", "bar"); ParameterizedTypeReference<?> typeReference = new ParameterizedTypeReference<List<String>>() {}; RequestEntity<?> entity = RequestEntity.post(url).body(body, typeReference.getType()); assertEquals(typeReference.getType(), entity.getType()); }
@Override public <T> ResponseEntity<T> exchange(RequestEntity<?> requestEntity, Class<T> responseType) throws RestClientException { return getRestTemplate(requestEntity.getUrl()).exchange(requestEntity, responseType); }
@Bean public IntegrationFlow httpReactiveInboundChannelAdapterFlow() { return IntegrationFlows .from(WebFlux.inboundChannelAdapter("/reactivePost") .requestMapping(m -> m.methods(HttpMethod.POST)) .requestPayloadType(ResolvableType.forClassWithGenerics(Flux.class, String.class)) .statusCodeFunction(e -> HttpMethod.POST.equals(e.getMethod()) ? HttpStatus.ACCEPTED : HttpStatus.BAD_REQUEST)) .channel(c -> c.queue("storeChannel")) .get(); }
private static Map<String, Object> getOpenidConfiguration(String issuer) { ParameterizedTypeReference<Map<String, Object>> typeReference = new ParameterizedTypeReference<Map<String, Object>>() {}; RestTemplate rest = new RestTemplate(); try { URI uri = UriComponentsBuilder.fromUriString(issuer + "/.well-known/openid-configuration") .build() .toUri(); RequestEntity<Void> request = RequestEntity.get(uri).build(); return rest.exchange(request, typeReference).getBody(); } catch(RuntimeException e) { throw new IllegalArgumentException("Unable to resolve the OpenID Configuration with the provided Issuer of " + "\"" + issuer + "\"", e); } }
@Override public boolean equals(@Nullable Object other) { if (this == other) { return true; } if (!super.equals(other)) { return false; } RequestEntity<?> otherEntity = (RequestEntity<?>) other; return (ObjectUtils.nullSafeEquals(getMethod(), otherEntity.getMethod()) && ObjectUtils.nullSafeEquals(getUrl(), otherEntity.getUrl())); }