下面列出了怎么用org.springframework.http.RequestEntity的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void freemarker() throws MessagingException, IOException {
RestTemplate rt = new RestTemplate();
// @formatter:off
UriComponentsBuilder builder = UriComponentsBuilder.fromPath(FREEMARKER_URL)
.scheme("http")
.host("localhost")
.port(port)
.queryParam("subject", "test")
.queryParam("template", "register-freemarker.html")
.queryParam("to", "[email protected]");
RequestEntity<NestedBean> request = RequestEntity.
post(builder.build().toUri()).
contentType(MediaType.APPLICATION_JSON).
body(new NestedBean(new SimpleBean("foo", 42)));
// @formatter:on
ResponseEntity<Void> response = rt.exchange(request, Void.class);
assertEquals("HTTP status should be 201: Created", HttpStatus.CREATED, response.getStatusCode());
AssertEmail.assertEquals(
new ExpectedEmail("test", new ExpectedContent(getClass().getResourceAsStream("/expected/ogham/register_foo_42.html"), "text/html.*"), "[email protected]", "[email protected]"),
greenMail.getReceivedMessages());
}
public ProfileTasks getProfileTaskList(final ProfileTaskQuery query) throws IOException {
final URL queryFileUrl = Resources.getResource("profileTaskList.gql");
final String queryString = Resources.readLines(queryFileUrl, StandardCharsets.UTF_8)
.stream()
.filter(it -> !it.startsWith("#"))
.collect(Collectors.joining())
.replace("{serviceId}", String.valueOf(query.serviceId()))
.replace("{endpointName}", query.endpointName());
final ResponseEntity<GQLResponse<ProfileTasks>> responseEntity = restTemplate.exchange(
new RequestEntity<>(queryString, HttpMethod.POST, URI.create(endpointUrl)),
new ParameterizedTypeReference<GQLResponse<ProfileTasks>>() {
}
);
if (responseEntity.getStatusCode() != HttpStatus.OK) {
throw new RuntimeException("Response status != 200, actual: " + responseEntity.getStatusCode());
}
return Objects.requireNonNull(responseEntity.getBody()).getData();
}
public ResponseEntity<byte[]> forwardHttpRequest(RequestData data, String traceId, MappingProperties mapping) {
ForwardDestination destination = resolveForwardDestination(data.getUri(), mapping);
prepareForwardedRequestHeaders(data, destination);
traceInterceptor.onForwardStart(traceId, destination.getMappingName(),
data.getMethod(), data.getHost(), destination.getUri().toString(),
data.getBody(), data.getHeaders());
RequestEntity<byte[]> request = new RequestEntity<>(data.getBody(), data.getHeaders(), data.getMethod(), destination.getUri());
ResponseData response = sendRequest(traceId, request, mapping, destination.getMappingMetricsName(), data);
log.debug(String.format("Forwarded: %s %s %s -> %s %d", data.getMethod(), data.getHost(), data.getUri(), destination.getUri(), response.getStatus().value()));
traceInterceptor.onForwardComplete(traceId, response.getStatus(), response.getBody(), response.getHeaders());
postForwardResponseInterceptor.intercept(response, mapping);
prepareForwardedResponseHeaders(response);
return status(response.getStatus())
.headers(response.getHeaders())
.body(response.getBody());
}
/** {@inheritDoc} */
@Override
public void logbackAccessEvent() {
RequestEntity<Void> request = RequestEntity
.get(rest.getRestTemplate().getUriTemplateHandler().expand("/test/text"))
.header("X-Forwarded-Port", "12345")
.build();
ResponseEntity<String> response = rest.exchange(request, String.class);
IAccessEvent event = LogbackAccessEventQueuingAppender.appendedEventQueue.pop();
LogbackAccessEventQueuingListener.appendedEventQueue.pop();
assertThat(response).hasStatusCode(HttpStatus.OK);
assertThat(event).hasLocalPort(port);
}
@Test
public void postWithRequestThatHasNonMatchingXPaths() throws Exception {
WireMockRestServiceServer.with(this.restTemplate) //
.baseUrl("https://example.org") //
.stubs("classpath:/mappings/body-matches-xpath.json").build();
ResponseEntity<String> response;
try {
response = this.restTemplate.exchange(
RequestEntity.post(URI.create("https://example.org/body"))
.contentType(MediaType.APPLICATION_XML).body("<foo/>"),
String.class);
}
catch (AssertionError e) {
response = null;
}
if (null != response) {
fail("There was a response for a request that shouldn't be matched : "
+ response);
}
}
@Test
public void postWithMoreExactHeaderMatch() throws Exception {
WireMockRestServiceServer.with(this.restTemplate) //
.baseUrl("https://example.org") // order determined by content...
.stubs("classpath:/mappings/header-matches.json",
"classpath:/mappings/header-matches-precise.json")
.build();
assertThat(
this.restTemplate
.exchange(
RequestEntity.post(new URI("https://example.org/poster"))
.accept(MediaType.valueOf("application/v.bar"))
.header("X-Precise", "true").build(),
String.class)
.getBody()).isEqualTo("Precise World");
}
public TemplateChangeStatus changeTemplate(DashboardSetting setting) throws IOException {
final URL queryFileUrl = Resources.getResource("ui-changeTemplate.gql");
final String queryString = Resources.readLines(queryFileUrl, StandardCharsets.UTF_8)
.stream()
.filter(it -> !it.startsWith("#"))
.collect(Collectors.joining())
.replace("{name}", setting.name())
.replace("{type}", String.valueOf(setting.type()))
.replace("{configuration}", setting.configuration())
.replace("{active}", String.valueOf(setting.active()));
final ResponseEntity<GQLResponse<TemplateChangeStatusWrapper>> responseEntity = restTemplate.exchange(
new RequestEntity<>(queryString, HttpMethod.POST, URI.create(endpointUrl)),
new ParameterizedTypeReference<GQLResponse<TemplateChangeStatusWrapper>>() {
}
);
if (responseEntity.getStatusCode() != HttpStatus.OK) {
throw new RuntimeException("Response status != 200, actual: " + responseEntity.getStatusCode());
}
return Objects.requireNonNull(responseEntity.getBody()).getData().getChangeStatusResult();
}
@Test
public void thymeleaf() throws MessagingException, IOException {
RestTemplate rt = new RestTemplate();
// @formatter:off
UriComponentsBuilder builder = UriComponentsBuilder.fromPath(THYMELEAF_URL)
.scheme("http")
.host("localhost")
.port(port)
.queryParam("subject", "test")
.queryParam("template", "register-thymeleaf")
.queryParam("to", "[email protected]");
RequestEntity<NestedBean> request = RequestEntity.
post(builder.build().toUri()).
contentType(MediaType.APPLICATION_JSON).
body(new NestedBean(new SimpleBean("foo", 42)));
// @formatter:on
ResponseEntity<Void> response = rt.exchange(request, Void.class);
assertEquals("HTTP status should be 201: Created", HttpStatus.CREATED, response.getStatusCode());
AssertEmail.assertEquals(
new ExpectedEmail("test", new ExpectedContent(getClass().getResourceAsStream("/expected/ogham/register_foo_42.html"), "text/html.*"), "[email protected]", "[email protected]"),
greenMail.getReceivedMessages());
}
@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());
}
public ReadMetrics readMetrics(final ReadMetricsQuery query) throws Exception {
final URL queryFileUrl = Resources.getResource("read-metrics.gql");
final String queryString = Resources.readLines(queryFileUrl, StandardCharsets.UTF_8)
.stream()
.filter(it -> !it.startsWith("#"))
.collect(Collectors.joining())
.replace("{step}", query.step())
.replace("{start}", query.start())
.replace("{end}", query.end())
.replace("{metricsName}", query.metricsName())
.replace("{serviceName}", query.serviceName())
.replace("{instanceName}", query.instanceName());
LOGGER.info("Query: {}", queryString);
final ResponseEntity<GQLResponse<ReadMetricsData>> responseEntity = restTemplate.exchange(
new RequestEntity<>(queryString, HttpMethod.POST, URI.create(endpointUrl)),
new ParameterizedTypeReference<GQLResponse<ReadMetricsData>>() {
}
);
if (responseEntity.getStatusCode() != HttpStatus.OK) {
throw new RuntimeException("Response status != 200, actual: " + responseEntity.getStatusCode());
}
return Objects.requireNonNull(responseEntity.getBody()).getData().getReadMetricsValues();
}
@Test
@DirtiesContext
public void testFluxFunctionPrimitive() throws Exception {
this.functionProperties.setDefinition("fluxuppercase");
ResponseEntity<String> postForEntity = this.rest
.exchange(RequestEntity.post(new URI("/functions/" + RoutingFunction.FUNCTION_NAME))
.contentType(MediaType.TEXT_PLAIN)
.body("[\"hello\", \"bye\"]"), String.class);
assertThat(postForEntity.getBody()).isEqualTo("[\"HELLO\", \"BYE\"]");
assertThat(postForEntity.getStatusCode()).isEqualTo(HttpStatus.OK);
postForEntity = this.rest.exchange(RequestEntity.post(new URI("/functions/" + RoutingFunction.FUNCTION_NAME))
.contentType(MediaType.TEXT_PLAIN)
.body("hello1"), String.class);
assertThat(postForEntity.getBody()).isEqualTo("HELLO1");
assertThat(postForEntity.getStatusCode()).isEqualTo(HttpStatus.OK);
// postForEntity = this.rest.exchange(RequestEntity.post(new URI("/functions/" + RoutingFunction.FUNCTION_NAME))
// .contentType(MediaType.TEXT_PLAIN)
// .body("hello2"), String.class);
// assertThat(postForEntity.getBody()).isEqualTo("HELLO2");
// assertThat(postForEntity.getStatusCode()).isEqualTo(HttpStatus.OK);
}
public TemplateChangeStatus addTemplate(DashboardSetting setting) throws IOException {
final URL queryFileUrl = Resources.getResource("ui-addTemplate.gql");
final String queryString = Resources.readLines(queryFileUrl, StandardCharsets.UTF_8)
.stream()
.filter(it -> !it.startsWith("#"))
.collect(Collectors.joining())
.replace("{name}", setting.name())
.replace("{type}", String.valueOf(setting.type()))
.replace("{configuration}", setting.configuration())
.replace("{active}", String.valueOf(setting.active()));
final ResponseEntity<GQLResponse<TemplateChangeStatusWrapper>> responseEntity = restTemplate.exchange(
new RequestEntity<>(queryString, HttpMethod.POST, URI.create(endpointUrl)),
new ParameterizedTypeReference<GQLResponse<TemplateChangeStatusWrapper>>() {
}
);
if (responseEntity.getStatusCode() != HttpStatus.OK) {
throw new RuntimeException("Response status != 200, actual: " + responseEntity.getStatusCode());
}
return Objects.requireNonNull(responseEntity.getBody()).getData().getChangeStatusResult();
}
@PostMapping(value = "/grumpy", produces = MediaType.APPLICATION_JSON_VALUE)
GrumpyResponse grumpy(@RequestBody GrumpyPerson person) {
//remove::start[]
//tag::controller[]
ResponseEntity<GrumpyBartenderResponse> response = this.restTemplate.exchange(
RequestEntity
.post(URI.create("http://localhost:" + this.port + "/buy"))
.contentType(MediaType.APPLICATION_JSON)
.body(person),
GrumpyBartenderResponse.class);
switch (response.getBody().status) {
case OK:
return new GrumpyResponse(response.getBody().message, "Enjoy!");
default:
return new GrumpyResponse(response.getBody().message, "Go to another bar");
}
//end::controller[]
//remove::end[return]
}
@GetMapping("/")
public String home(
@RequestParam(defaultValue = "test") String user,
@RequestParam(defaultValue = "LOW") String level
) throws URISyntaxException {
AuthnContext authnContext = AuthnContext.valueOf(level);
String jwtToken = Jwts.builder()
.setSubject(user)
.claim("AuthnContext", authnContext.name())
.signWith(SignatureAlgorithm.HS512, jwtSecret)
.compact();
HttpHeaders headers = new HttpHeaders();
headers.set(JwtAuthorizationHeaderFilter.JWT_HEADER_NAME, jwtToken);
log.debug("JWT: " + jwtToken);
RequestEntity<Object> requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8080/rest"));
ResponseEntity<String> responseEntity = restTemplate.exchange(requestEntity, String.class);
return "Got: " + responseEntity.getBody();
//some idea for propagating it over thread :https://stackoverflow.com/questions/46729203/propagate-http-header-jwt-token-over-services-using-spring-rest-template
}
@RequestMapping(method = RequestMethod.POST,
value = "/beer",
consumes = MediaType.APPLICATION_JSON_VALUE)
public String gimmeABeer(@RequestBody Person person) {
//remove::start[]
//tag::controller[]
ResponseEntity<Response> response = this.restTemplate.exchange(
RequestEntity
.post(URI.create("http://localhost:" + this.port + "/check"))
.contentType(MediaType.APPLICATION_JSON)
.body(person),
Response.class);
switch (response.getBody().status) {
case OK:
return "THERE YOU GO";
default:
return "GET LOST";
}
//end::controller[]
//remove::end[return]
}
@Test
public void testBodyAndCustomHeaderFromMessagePropagation() throws Exception {
// test POJO paylod
ResponseEntity<String> postForEntity = this.rest
.exchange(RequestEntity.post(new URI("/functions/employee"))
.contentType(MediaType.APPLICATION_JSON)
.body("{\"name\":\"Bob\",\"age\":25}"), String.class);
assertThat(postForEntity.getBody()).isEqualTo("{\"name\":\"Bob\",\"age\":25}");
assertThat(postForEntity.getHeaders().containsKey("x-content-type")).isTrue();
assertThat(postForEntity.getHeaders().get("x-content-type").get(0))
.isEqualTo("application/xml");
assertThat(postForEntity.getHeaders().get("foo").get(0)).isEqualTo("bar");
// test simple type payload
postForEntity = this.rest.postForEntity(new URI("/functions/string"),
"{\"name\":\"Bob\",\"age\":25}", String.class);
assertThat(postForEntity.getBody()).isEqualTo("{\"name\":\"Bob\",\"age\":25}");
assertThat(postForEntity.getHeaders().containsKey("x-content-type")).isTrue();
assertThat(postForEntity.getHeaders().get("x-content-type").get(0))
.isEqualTo("application/xml");
assertThat(postForEntity.getHeaders().get("foo").get(0)).isEqualTo("bar");
}
@Test
public void postFlux() throws Exception {
ResponseEntity<List<Bar>> result = rest.exchange(
RequestEntity
.post(rest.getRestTemplate().getUriTemplateHandler()
.expand("/flux/bars"))
.body(Collections
.singletonList(Collections.singletonMap("name", "foo"))),
new ParameterizedTypeReference<List<Bar>>() {
});
assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(result.getBody().iterator().next().getName()).isEqualTo("hello foo");
}
@Test
public void count() throws Exception {
List<String> list = Arrays.asList("A", "B", "A");
assertThat(this.rest.exchange(
RequestEntity.post(new URI("/count")).accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON).body(list),
String.class).getBody()).isEqualTo("{\"A\":2,\"B\":1}");
}
@Test
public void foos() throws Exception {
ResponseEntity<String> result = this.rest
.exchange(RequestEntity.get(new URI("/foos")).build(), String.class);
assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(result.getBody())
.isEqualTo("[{\"value\":\"foo\"},{\"value\":\"bar\"}]");
}
@Async
public <T> Future<Resources<T>> getDataList(URI url, TypeReferences.ResourcesType<T> type) throws
InterruptedException, IOException {
RequestEntity<Void> request = RequestEntity.get(url).accept(HAL_JSON).build();
LOG.debug("Requesting: " + request.toString());
Resources<T> body = restProxyTemplate.getRestTemplate().exchange(request, type).getBody();
LOG.debug("Received: " + body.toString());
return new AsyncResult<>(body);
}
@GetMapping("HELLO")
public String app(@RequestParam("code") String code) {
String accessToken = accessToken(code);
RequestEntity<Void> request =
RequestEntity.get(URI.create("http://localhost:8080/hello"))
.header(HttpHeaders.AUTHORIZATION, baerer(accessToken))
.build();
return restTemplate.exchange(request, String.class).getBody().toUpperCase();
}
@Test
public void index() {
RequestEntity<Void> request = RequestEntity
.get(URI.create("http://localhost:8080/messages/"))
.accept(MediaType.APPLICATION_JSON)
.build();
ResponseEntity<List<Message>> response = restTemplate
.exchange(request,new ParameterizedTypeReference<List<Message>>(){});
List<Message> messages = response.getBody();
assertTrue(messages.size() > 0);
}
@Test
public void wordsJson() throws Exception {
assertThat(this.rest
.exchange(RequestEntity.get(new URI("/words"))
.accept(MediaType.APPLICATION_JSON).build(), String.class)
.getBody()).isEqualTo("[\"foo\",\"bar\"]");
}
public JsonNode getDependencies(String bootVersion) throws Exception {
if (!dependencyMetaMap.containsKey(bootVersion)) {
// set connection timeouts
timeoutFromPrefs();
// prepare request
final String serviceUrl = NbPreferences.forModule(PrefConstants.class).get(PREF_INITIALIZR_URL,
PrefConstants.DEFAULT_INITIALIZR_URL);
UriTemplate template = new UriTemplate(serviceUrl.concat("/dependencies?bootVersion={bootVersion}"));
RequestEntity<Void> req = RequestEntity
.get(template.expand(bootVersion))
.accept(MediaType.valueOf("application/vnd.initializr.v2.1+json"))
.header("User-Agent", REST_USER_AGENT)
.build();
// connect
logger.log(INFO, "Getting Spring Initializr dependencies metadata from: {0}", template);
logger.log(INFO, "Asking metadata as: {0}", REST_USER_AGENT);
long start = System.currentTimeMillis();
ResponseEntity<String> respEntity = rt.exchange(req, String.class);
// analyze response
final HttpStatus statusCode = respEntity.getStatusCode();
if (statusCode == OK) {
ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
final JsonNode depMeta = mapper.readTree(respEntity.getBody());
logger.log(INFO, "Retrieved Spring Initializr dependencies metadata for boot version {0}. Took {1} msec",
new Object[]{bootVersion, System.currentTimeMillis() - start});
if (logger.isLoggable(FINE)) {
logger.fine(mapper.writeValueAsString(depMeta));
}
dependencyMetaMap.put(bootVersion, depMeta);
} else {
// log status code
final String errMessage = String.format("Spring initializr service connection problem. HTTP status code: %s",
statusCode.toString());
logger.severe(errMessage);
// throw exception in order to set error message
throw new RuntimeException(errMessage);
}
}
return dependencyMetaMap.get(bootVersion);
}
@Override
public <T> ResponseEntity<T> exchange(RequestEntity<?> requestEntity, Class<T> responseType)
throws RestClientException {
Assert.notNull(requestEntity, "'requestEntity' must not be null");
RequestCallback requestCallback = httpEntityCallback(requestEntity, responseType);
ResponseExtractor<ResponseEntity<T>> responseExtractor = responseEntityExtractor(responseType);
return execute(requestEntity.getUrl(), requestEntity.getMethod(), requestCallback, responseExtractor);
}
@Test
public void create() {
Message message = new Message("new message");
RequestEntity<Message> request = RequestEntity
.post(URI.create("http://localhost:8080/messages/"))
.contentType(MediaType.APPLICATION_JSON)
.body(message);
ResponseEntity<Resource<Message>> response =
restTemplate.exchange(request, new ParameterizedTypeReference<Resource<Message>>(){});
assertEquals(response.getBody().getContent().getText(), "new message");
}
private void post(byte[] json) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
RequestEntity<byte[]> requestEntity = new RequestEntity<byte[]>(json, httpHeaders,
HttpMethod.POST, URI.create(this.url));
this.restTemplate.exchange(requestEntity, String.class);
}
@RequestMapping(method = RequestMethod.POST,
value = "/wasted",
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public Response gimmeABeer(@RequestBody Person person) throws MalformedURLException {
//remove::start[]
return this.restTemplate.exchange(
RequestEntity
.post(URI.create("http://localhost:" + this.port + "/beer"))
.contentType(MediaType.APPLICATION_JSON)
.body(person),
Response.class).getBody();
//remove::end[return]
}
@Test // SPR-13154
public void jsonPostForObjectWithJacksonTypeInfoList() throws URISyntaxException {
List<ParentClass> list = new ArrayList<>();
list.add(new Foo("foo"));
list.add(new Bar("bar"));
ParameterizedTypeReference<?> typeReference = new ParameterizedTypeReference<List<ParentClass>>() {};
RequestEntity<List<ParentClass>> entity = RequestEntity
.post(new URI(baseUrl + "/jsonpost"))
.contentType(new MediaType("application", "json", StandardCharsets.UTF_8))
.body(list, typeReference.getType());
String content = template.exchange(entity, String.class).getBody();
assertTrue(content.contains("\"type\":\"foo\""));
assertTrue(content.contains("\"type\":\"bar\""));
}
@Test
public void timeoutJson() throws Exception {
assertThat(this.rest
.exchange(RequestEntity.get(new URI("/timeout"))
.accept(MediaType.APPLICATION_JSON).build(), String.class)
.getBody()).isEqualTo("[\"foo\"]");
}