下面列出了org.springframework.http.ResponseEntity#getBody ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void checkJobExecuteStatus(ResponseEntity<Map> responseEntity, Map<String, Boolean> jobExecuteStatus) {
Map<?, ?> responseData = responseEntity.getBody();
List<?> runningJob = (List<?>)responseData.get("running");
if (runningJob != null) {
for (Object job : runningJob) {
Map<?, ?> jobInfo = (Map<?, ?>)job;
String jobName = (String) jobInfo.get("name");
Boolean status = jobExecuteStatus.get(jobName);
if (status != null) {
jobExecuteStatus.put(jobName, true);
}
}
}
}
@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]
}
protected void fetchFromGithub() {
if (next != null) {
return;
}
if (uri == null) {
return;
}
ResponseEntity<E> entity = getReponseEntity();
List<String> headerValues = entity.getHeaders().get("Link");
if (headerValues == null) {
uri = null;
} else {
String first = headerValues.get(0);
if (StringUtils.hasText(first)) {
Optional<LinkRelation> linkRelation = linkRelationExtractor.extractLinkRelation(first, LinkRelation.NEXT);
if (linkRelation.isPresent()) {
uri = URI.create(linkRelation.get().getLink());
}else{
uri = null;
}
}
}
next = entity.getBody();
}
@Test
public void IsCustomerListReturned() {
Iterable<Customer> customers = customerRepository.findAll();
assertTrue(StreamSupport.stream(customers.spliterator(), false)
.noneMatch(c -> (c.getName().equals("Hoeller1"))));
ResponseEntity<String> resultEntity = restTemplate.getForEntity(
customerURL() + "/list.html", String.class);
assertTrue(resultEntity.getStatusCode().is2xxSuccessful());
String customerList = resultEntity.getBody();
assertFalse(customerList.contains("Hoeller1"));
customerRepository.save(new Customer("Juergen", "Hoeller1",
"[email protected]", "Schlossallee", "Linz"));
customerList = restTemplate.getForObject(customerURL() + "/list.html",
String.class);
assertTrue(customerList.contains("Hoeller1"));
}
@Override
public Release scale(String releaseName, ScaleRequest scaleRequest) {
ParameterizedTypeReference<Release> typeReference =
new ParameterizedTypeReference<Release>() { };
Map<String, String> uriVariables = new HashMap<String, String>();
uriVariables.put("releaseName", releaseName);
HttpEntity<ScaleRequest> httpEntity = new HttpEntity<>(scaleRequest);
ResponseEntity<Release> resourceResponseEntity =
restTemplate.exchange(baseUri + "/release/scale/{releaseName}",
HttpMethod.POST,
httpEntity,
typeReference,
uriVariables);
return resourceResponseEntity.getBody();
}
@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]
}
@Test
public void testDmnRestApiIntegrationWithAuthentication() {
String processDefinitionsUrl = "http://localhost:" + serverPort + "/dmn-api/dmn-repository/deployments";
HttpEntity<?> request = new HttpEntity<>(createHeaders("filiphr", "password"));
ResponseEntity<DataResponse<DmnDeploymentResponse>> response = restTemplate
.exchange(processDefinitionsUrl, HttpMethod.GET, request, new ParameterizedTypeReference<DataResponse<DmnDeploymentResponse>>() {
});
assertThat(response.getStatusCode())
.as("Status code")
.isEqualTo(HttpStatus.OK);
DataResponse<DmnDeploymentResponse> deployments = response.getBody();
assertThat(deployments).isNotNull();
assertThat(deployments.getData())
.isEmpty();
assertThat(deployments.getTotal()).isZero();
}
@Test
void should_ChangeValueOfModified_When_UpdatingTask() {
ResponseEntity<TaskRepresentationModel> responseGet =
template.exchange(
restHelper.toUrl(Mapping.URL_TASKS_ID, "TKI:100000000000000000000000000000000000"),
HttpMethod.GET,
new HttpEntity<>(restHelper.getHeadersTeamlead_1()),
TASK_MODEL_TYPE);
final TaskRepresentationModel originalTask = responseGet.getBody();
ResponseEntity<TaskRepresentationModel> responseUpdate =
template.exchange(
restHelper.toUrl(Mapping.URL_TASKS_ID, "TKI:100000000000000000000000000000000000"),
HttpMethod.PUT,
new HttpEntity<>(originalTask, restHelper.getHeadersTeamlead_1()),
TASK_MODEL_TYPE);
TaskRepresentationModel updatedTask = responseUpdate.getBody();
assertThat(originalTask).isNotNull();
assertThat(updatedTask).isNotNull();
assertThat(originalTask.getModified()).isBefore(updatedTask.getModified());
}
private FraudServiceResponse sendRequestToFraudDetectionService(
FraudServiceRequest request) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add(HttpHeaders.CONTENT_TYPE, FRAUD_SERVICE_JSON_VERSION_1);
// tag::client_call_server[]
ResponseEntity<FraudServiceResponse> response = restTemplate.exchange(
"http://localhost:" + getPort() + "/fraudcheck", HttpMethod.PUT,
new HttpEntity<>(request, httpHeaders), FraudServiceResponse.class);
// end::client_call_server[]
return response.getBody();
}
@Test
public void mvcEndpoint() throws Throwable {
AnnotationConfigEmbeddedWebApplicationContext applicationContext =
new AnnotationConfigEmbeddedWebApplicationContext(CallbackEmbeddedContainerCustomizer.class, EmbeddedContainerConfiguration.class, EndpointConfiguration.class);
ProcessEngine processEngine = applicationContext.getBean(ProcessEngine.class);
org.junit.Assert.assertNotNull("the processEngine should not be null", processEngine);
ProcessEngineEndpoint processEngineEndpoint =
applicationContext.getBean(ProcessEngineEndpoint.class);
org.junit.Assert.assertNotNull("the processEngineEndpoint should not be null", processEngineEndpoint);
RestTemplate restTemplate = applicationContext.getBean(RestTemplate.class);
ResponseEntity<Map> mapResponseEntity =
restTemplate.getForEntity("http://localhost:9091/activiti/", Map.class);
Map map = mapResponseEntity.getBody();
String[] criticalKeys = {"completedTaskCount", "openTaskCount", "cachedProcessDefinitionCount"};
Map<?, ?> invokedResults = processEngineEndpoint.invoke();
for (String k : criticalKeys) {
org.junit.Assert.assertTrue(map.containsKey(k));
org.junit.Assert.assertEquals(((Number) map.get(k)).longValue(), ((Number) invokedResults.get(k)).longValue());
}
}
@Test
public void shouldCreateCustomConnectorInfoForUploadedSwagger() throws IOException {
final ConnectorSettings connectorSettings = new ConnectorSettings.Builder().connectorTemplateId(TEMPLATE_ID).build();
final ResponseEntity<Connector> response = post("/api/v1/connectors/custom",
multipartBodyForInfo(connectorSettings, getClass().getResourceAsStream("/io/syndesis/server/runtime/test-swagger.json")),
Connector.class, tokenRule.validToken(), HttpStatus.OK, multipartHeaders());
final Connector got = response.getBody();
assertThat(got).isNotNull();
}
private <T> T getForMediaType(Class<T> value, MediaType mediaType,
String url) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(mediaType));
HttpEntity<String> entity = new HttpEntity<String>("parameters",
headers);
ResponseEntity<T> resultEntity = restTemplate.exchange(url,
HttpMethod.GET, entity, value);
return resultEntity.getBody();
}
@Test
public void testExchangeWithRequestEntityForPostWithRequestParam_Map_Header() {
//因为post请求有请求体application/x-www-form-urlencoded,RequestParam需要拼到url字符串中,
// 因为postForEntity中没有urlVariables,只有uriVariables,因此RequestParam只能放到request中的form请求体中
String userId = "1";
int pageId = 0;
int pageSize = 10;
String auth = "secret In Header";
Result excepted = new Result(userId, pageId, pageSize, auth);
String url = domain + "/" + userId + "/auth";//userId是uriVariables;?pageId={pageId}&pageSize={pageSize}不是uri,需要放在request请求体中
//Header只能使用MultiValueMap类型
MultiValueMap<String, String> header = new LinkedMultiValueMap<>();
header.add("auth", auth);
//如果给定一个MultiValueMap<String,String>,
// 那么这个Map中的值将会被FormHttpMessageConverter以"application/x-www-form-urlencoded"的格式写到请求体中
//java.util.Map中存放的数据,不会放到request请求的请求体中,只能是org.springframework.util.MultiValueMap
MultiValueMap<String, Integer> body = new LinkedMultiValueMap<>();
body.add("pageId", pageId);
body.add("pageSize", pageSize);
//RequestEntity中只有有body,header,PathVariable这种参数,就只能自己拼字符串喽
RequestEntity<MultiValueMap<String, Integer>> requestEntity = new RequestEntity<>(body, header, HttpMethod.POST, URI.create(url));
ResponseEntity<Result> forEntity = restTemplate.exchange(requestEntity, Result.class);
Result actual = forEntity.getBody();
assertThat(actual, is(excepted));
}
@Override
public Bar create(Bar object) throws JsonProcessingException {
HttpEntity<String> entity = getJsonEntity(new NewBar(object));
ResponseEntity<Bar> responseEntity = restTemplate.postForEntity(getUrl("bars"), entity, Bar.class);
return responseEntity.getBody();
}
public ResultEntity queryOutPutTopics(Integer projectId, Integer topoId) {
ResponseEntity<ResultEntity> result = sender.get(ServiceNames.KEEPER_SERVICE, "/project-topos/out-topics/{0}/{1}", StringUtils.EMPTY, projectId, topoId);
return result.getBody();
}
public ResultEntity updateUser(User user) {
ResponseEntity<ResultEntity> result = sender.post(MS_SERVICE, "/users/update/" + user.getId(), user);
return result.getBody();
}
private Person getPerson(String name) {
String url = "http://localhost:8081/getPerson/" + name;
ResponseEntity<Person> response = restTemplate.getForEntity(url, Person.class);
return response.getBody();
}
/**
* Issue a PUT REST call that returns a response object. This is typically an update.
*
* @param <T> type of the return object
* @param methodName name of the method being called.
* @param returnClass class of the response object.
* @param urlTemplate template of the URL for the REST API call with place-holders for the parameters.
* @param requestBody request body for the request.
* @param params a list of parameters that are slotted into the url template.
*
* @return Object
* @throws RESTServerException something went wrong with the REST call stack.
*/
public <T> T callPutRESTCall(String methodName,
Class<T> returnClass,
String urlTemplate,
Object requestBody,
Object... params) throws RESTServerException
{
try
{
log.debug("Calling " + methodName + " with URL template " + urlTemplate + " and parameters " + Arrays.toString(params) + ".");
HttpEntity<?> request = new HttpEntity<>(requestBody);
if (requestBody == null)
{
// continue with a null body, we may want to fail this request here in the future.
log.warn("Poorly formed PUT call made by " + methodName);
}
if (basicAuthorizationHeader != null)
{
request = new HttpEntity<>(requestBody, basicAuthorizationHeader);
}
ResponseEntity<T> responseEntity = restTemplate.exchange(urlTemplate, HttpMethod.PUT, request, returnClass, params);
T responseObject = responseEntity.getBody();
if (responseObject != null)
{
log.debug("Returning from " + methodName + " with response object " + responseObject.toString() + ".");
}
else
{
log.debug("Returning from " + methodName + " with no response object.");
}
return responseObject;
}
catch (Throwable error)
{
log.debug("Exception " + error.getClass().getName() + " with message " + error.getMessage() + " occurred during REST call for " + methodName + ".");
RESTClientConnectorErrorCode errorCode = RESTClientConnectorErrorCode.CLIENT_SIDE_REST_API_ERROR;
String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(error.getClass().getName(),
methodName,
urlTemplate,
serverName,
serverPlatformURLRoot,
error.getMessage());
throw new RESTServerException(errorCode.getHTTPErrorCode(),
this.getClass().getName(),
methodName,
errorMessage,
errorCode.getSystemAction(),
errorCode.getUserAction(),
error);
}
}
protected void checkMetrics(String kind, String backend, float count) {
ResponseEntity<String> metricsResponse = restTemplate.getForEntity("/actuator/prometheus", String.class);
assertThat(metricsResponse.getBody()).isNotNull();
String response = metricsResponse.getBody();
assertThat(response).contains(getMetricName(kind, backend) + String.format("%.1f", count));
}
public ResultEntity findAllTables(String queryString) {
ResponseEntity<ResultEntity> result = sender.get(ServiceNames.KEEPER_SERVICE, "/tables/findAll", queryString);
return result.getBody();
}