org.springframework.http.RequestEntity Java Examples

The following examples show how to use org.springframework.http.RequestEntity. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BeerController.java    From spring-cloud-contract-samples with Apache License 2.0 7 votes vote down vote up
@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]
}
 
Example #2
Source File: RoutingFunctionTests.java    From spring-cloud-function with Apache License 2.0 6 votes vote down vote up
@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);
	}
 
Example #3
Source File: OghamAutoConfigurationOghamPropertiesPrecedenceTest.java    From ogham with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #4
Source File: HttpEntityMethodProcessorMockTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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());
}
 
Example #5
Source File: UIConfigurationManagementClient.java    From skywalking with Apache License 2.0 6 votes vote down vote up
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();
    }
 
Example #6
Source File: UIConfigurationManagementClient.java    From skywalking with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #7
Source File: SimpleQueryClient.java    From skywalking with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #8
Source File: GrumpyBartenderController.java    From spring-cloud-contract-samples with Apache License 2.0 6 votes vote down vote up
@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]
}
 
Example #9
Source File: WiremockMockServerApplicationTests.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example #10
Source File: WiremockMockServerApplicationTests.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
@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);
	}
}
 
Example #11
Source File: TomcatServerPortUnusingTest.java    From logback-access-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
/** {@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);

}
 
Example #12
Source File: RequestForwarder.java    From staffjoy with MIT License 6 votes vote down vote up
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());

}
 
Example #13
Source File: ProfileClient.java    From skywalking with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #14
Source File: OghamAutoConfigurationOghamPropertiesOnlyTest.java    From ogham with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #15
Source File: PeacefulController.java    From training with MIT License 6 votes vote down vote up
@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
}
 
Example #16
Source File: HeadersToMessageTests.java    From spring-cloud-function with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example #17
Source File: HttpOperationsTest.java    From riptide with MIT License 5 votes vote down vote up
@Test
void shouldExchange() {
    driver.addExpectation(onRequestTo("/departments/1/users")
                    .withMethod(Method.POST)
                    .withBody("{\"name\":\"D. Fault\",\"birthday\":\"1984-09-13\"}", "application/json"),
            giveResponse("{\"name\":\"D. Fault\",\"birthday\":\"1984-09-13\"}", "application/json"));

    final User user = new HttpOperations(http).exchange(new RequestEntity<>(new User("D. Fault", "1984-09-13"),
            POST, URI.create("/departments/1/users")), User.class).getBody();

    assertEquals(new User("D. Fault", "1984-09-13"), user);
}
 
Example #18
Source File: HttpGetIntegrationTests.java    From spring-cloud-function with Apache License 2.0 5 votes vote down vote up
@Test
public void errorJson() throws Exception {
	assertThat(this.rest
			.exchange(RequestEntity.get(new URI("/bang"))
					.accept(MediaType.APPLICATION_JSON).build(), String.class)
			.getBody()).isEqualTo("[\"foo\"]");
}
 
Example #19
Source File: HttpGetIntegrationTests.java    From spring-cloud-function with Apache License 2.0 5 votes vote down vote up
@Test
public void word() throws Exception {
	ResponseEntity<String> result = this.rest
			.exchange(RequestEntity.get(new URI("/word")).build(), String.class);
	assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK);
	assertThat(result.getBody()).isEqualTo("foo");
}
 
Example #20
Source File: HttpPostIntegrationTests.java    From spring-cloud-function with Apache License 2.0 5 votes vote down vote up
@Test
public void messages() throws Exception {
	ResponseEntity<String> result = this.rest.exchange(RequestEntity
			.post(new URI("/messages")).contentType(MediaType.APPLICATION_JSON)
			.header("x-foo", "bar").body("[\"foo\",\"bar\"]"), String.class);
	assertThat(result.getHeaders().getFirst("x-foo")).isEqualTo("bar");
	assertThat(result.getHeaders()).doesNotContainKey("id");
	assertThat(result.getBody()).isEqualTo("[\"(FOO)\",\"(BAR)\"]");
}
 
Example #21
Source File: HttpPostIntegrationTests.java    From spring-cloud-function with Apache License 2.0 5 votes vote down vote up
@Test
public void addFoos() throws Exception {
	ResponseEntity<String> result = this.rest.exchange(RequestEntity
			.post(new URI("/addFoos")).contentType(MediaType.APPLICATION_JSON)
			.body("[{\"value\":\"foo\"},{\"value\":\"bar\"}]"), String.class);
	assertThat(result.getStatusCode()).isEqualTo(HttpStatus.ACCEPTED);
	assertThat(this.test.list).hasSize(2);
	assertThat(result.getBody()).isEqualTo(null);
}
 
Example #22
Source File: HttpPostIntegrationTests.java    From spring-cloud-function with Apache License 2.0 5 votes vote down vote up
@Test
public void updates() throws Exception {
	ResponseEntity<String> result = this.rest.exchange(RequestEntity
			.post(new URI("/updates")).contentType(MediaType.APPLICATION_JSON)
			.body("[\"one\", \"two\"]"), String.class);
	assertThat(result.getStatusCode()).isEqualTo(HttpStatus.ACCEPTED);
	assertThat(this.test.list).hasSize(2);
	assertThat(result.getBody()).isNull();
}
 
Example #23
Source File: HttpGetIntegrationTests.java    From spring-cloud-function with Apache License 2.0 5 votes vote down vote up
@Test
public void sentencesAcceptAny() throws Exception {
	assertThat(
			this.rest
					.exchange(RequestEntity.get(new URI("/sentences"))
							.accept(MediaType.ALL).build(), String.class)
					.getBody()).isEqualTo("[[\"go\",\"home\"],[\"come\",\"back\"]]");
}
 
Example #24
Source File: OAuth2ConfigResourceClient.java    From spring-cloud-services-starters with Apache License 2.0 5 votes vote down vote up
private Resource getResource(String profile, String label, String path, ResourceType resourceType) {
	Assert.isTrue(configClientProperties.getName() != null && !configClientProperties.getName().isEmpty(),
			"Spring application name is undefined.");

	Assert.notEmpty(configClientProperties.getUri(), "Config server URI is undefined");
	Assert.hasText(configClientProperties.getUri()[0], "Config server URI is undefined.");

	if (profile == null) {
		profile = configClientProperties.getProfile();
		if (profile == null || profile.isEmpty()) {
			profile = "default";
		}
	}

	if (label == null) {
		label = configClientProperties.getLabel();
	}

	UriComponentsBuilder urlBuilder = UriComponentsBuilder.fromHttpUrl(configClientProperties.getUri()[0])
			.pathSegment(configClientProperties.getName()).pathSegment(profile).pathSegment(label)
			.pathSegment(path);
	if (label == null) {
		urlBuilder.queryParam("useDefaultLabel");
	}
	RequestEntity.HeadersBuilder<?> requestBuilder = RequestEntity.get(urlBuilder.build().toUri());
	if (StringUtils.hasText(configClientProperties.getToken())) {
		requestBuilder.header(TOKEN_HEADER, configClientProperties.getToken());
	}
	if (resourceType == ResourceType.BINARY) {
		requestBuilder.accept(MediaType.APPLICATION_OCTET_STREAM);
	}

	ResponseEntity<Resource> forEntity = restTemplate.exchange(requestBuilder.build(), Resource.class);
	return forEntity.getBody();
}
 
Example #25
Source File: HttpGetIntegrationTests.java    From spring-cloud-function with Apache License 2.0 5 votes vote down vote up
@Test
public void postMoreFoo() throws Exception {
	ResponseEntity<String> result = this.rest.exchange(RequestEntity
			.get(new URI("/post/more/foo")).accept(MediaType.TEXT_PLAIN).build(),
			String.class);
	assertThat(result.getBody()).isEqualTo("(FOO)");
}
 
Example #26
Source File: RestTemplateSaganClient.java    From spring-cloud-release-tools with Apache License 2.0 5 votes vote down vote up
@Override
public Project updateRelease(String projectName, List<ReleaseUpdate> releaseUpdates) {
	RequestEntity<List<ReleaseUpdate>> request = RequestEntity
			.put(URI.create(
					this.baseUrl + "/project_metadata/" + projectName + "/releases"))
			.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE)
			.body(releaseUpdates);
	ResponseEntity<Project> entity = this.restTemplate.exchange(request,
			Project.class);
	Project project = entity.getBody();
	log.info("Response from Sagan\n\n[{}] \n with body [{}]", entity, project);
	return project;
}
 
Example #27
Source File: AsyncGetService.java    From orders with Apache License 2.0 5 votes vote down vote up
@Async
public <T, B> Future<T> postResource(URI uri, B body, ParameterizedTypeReference<T> returnType) {
    RequestEntity<B> request = RequestEntity.post(uri).contentType(MediaType.APPLICATION_JSON).accept(MediaType
            .APPLICATION_JSON).body(body);
    LOG.debug("Requesting: " + request.toString());
    T responseBody = restProxyTemplate.getRestTemplate().exchange(request, returnType).getBody();
    LOG.debug("Received: " + responseBody);
    return new AsyncResult<>(responseBody);
}
 
Example #28
Source File: WiremockMockServerApplicationTests.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Test
public void postWithHeaderMatches() throws Exception {
	WireMockRestServiceServer.with(this.restTemplate) //
			.baseUrl("https://example.org") // order determined by content...
			.stubs("classpath:/mappings/poster.json",
					"classpath:/mappings/header-matches.json")
			.build();
	assertThat(this.restTemplate.exchange(
			RequestEntity.post(new URI("https://example.org/poster"))
					.accept(MediaType.valueOf("application/v.bar")).build(),
			String.class).getBody()).isEqualTo("Bar World");
}
 
Example #29
Source File: ReactiveTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void post() throws Exception {
	ResponseEntity<List<Bar>> result = rest.exchange(
			RequestEntity
					.post(rest.getRestTemplate().getUriTemplateHandler()
							.expand("/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");
}
 
Example #30
Source File: HttpPostIntegrationTests.java    From spring-cloud-function with Apache License 2.0 5 votes vote down vote up
@Test
public void postMore() throws Exception {
	ResponseEntity<String> result = this.rest.exchange(RequestEntity
			.post(new URI("/post/more")).contentType(MediaType.APPLICATION_JSON)
			.body("[\"foo\",\"bar\"]"), String.class);
	assertThat(result.getBody()).isEqualTo("[\"(FOO)\",\"(BAR)\"]");
}