本文整理汇总了Java中org.springframework.http.ResponseEntity.getBody方法的典型用法代码示例。如果您正苦于以下问题:Java ResponseEntity.getBody方法的具体用法?Java ResponseEntity.getBody怎么用?Java ResponseEntity.getBody使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.springframework.http.ResponseEntity
的用法示例。
在下文中一共展示了ResponseEntity.getBody方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getUserInfoFor
import org.springframework.http.ResponseEntity; //导入方法依赖的package包/类
public Map<String, String> getUserInfoFor(OAuth2AccessToken accessToken) {
RestTemplate restTemplate = new RestTemplate();
RequestEntity<Void> requestEntity = new RequestEntity<>(
getHeader(accessToken.getValue()),
HttpMethod.GET,
URI.create(properties.getUserInfoUri())
);
ParameterizedTypeReference<Map<String, String>> typeRef =
new ParameterizedTypeReference<Map<String, String>>() {};
ResponseEntity<Map<String, String>> result = restTemplate.exchange(
requestEntity, typeRef);
if (result.getStatusCode().is2xxSuccessful()) {
return result.getBody();
}
throw new RuntimeException("It wasn't possible to retrieve userInfo");
}
示例2: getComments
import org.springframework.http.ResponseEntity; //导入方法依赖的package包/类
@HystrixCommand(fallbackMethod = "defaultComments")
public List<Comment> getComments(Image image, String sessionId) {
ResponseEntity<List<Comment>> results = restTemplate.exchange(
"http://COMMENTS/comments/{imageId}",
HttpMethod.GET,
new HttpEntity<>(new HttpHeaders() {{
String credentials = imagesConfiguration.getCommentsUser() + ":" +
imagesConfiguration.getCommentsPassword();
String token = new String(Base64Utils.encode(credentials.getBytes()));
set(AUTHORIZATION, "Basic " + token);
set("Cookie", "SESSION=" + sessionId);
}}),
new ParameterizedTypeReference<List<Comment>>() {},
image.getId());
return results.getBody();
}
示例3: getResourcesFromGet
import org.springframework.http.ResponseEntity; //导入方法依赖的package包/类
/**
* Get the resources for a given URL. It can throw a number of RuntimeExceptions (connection not
* found etc - which are all wrapped in a RestClientException).
*
* @param rt the RestTemplate to use
* @param targetURI the url to access
* @return the returns object or null if not found
*/
public R getResourcesFromGet(final RestTemplate rt, final URI targetURI) {
ResponseEntity<R> resp = rt.getForEntity(targetURI, getTypeClass());
if (resp != null) {
if (LOG.isDebugEnabled()) {
LOG.debug("response is not null: " + resp.getStatusCode());
}
if (resp.getStatusCode() == HttpStatus.OK) {
if (LOG.isDebugEnabled()) {
LOG.debug("response is OK");
}
this.processHeaders(targetURI, resp.getHeaders());
return resp.getBody();
} else {
return null;
}
} else {
return null;
}
}
示例4: getMarathonServiceDetails
import org.springframework.http.ResponseEntity; //导入方法依赖的package包/类
public String getMarathonServiceDetails() {
try {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> responseEntity =
restTemplate.exchange(props.getMarathon().getUrl() + "/v2/apps", HttpMethod.GET, null, String.class);
if (responseEntity.getStatusCode().value() != 200) {
LOG.error("error marathon service failed with status code " + responseEntity.getStatusCode().value());
return null;
}
isHealthy = true;
if (LOG.isTraceEnabled()) {
LOG.trace("marathon services details: " + responseEntity.getBody());
}
return responseEntity.getBody();
} catch (RestClientException e) {
LOG.error("error in calling marathon service details: ", e);
isHealthy = false;
return null;
}
}
示例5: saveResultForClass
import org.springframework.http.ResponseEntity; //导入方法依赖的package包/类
private String saveResultForClass(String sourcedId) {
Map<String, String> resultMetadata = Collections.singletonMap(Vocabulary.TENANT, TestData.TENANT_1);
Result result =
new Result.Builder()
.withResultstatus("Grade B")
.withScore(70.0)
.withComment("not bad")
.withMetadata(resultMetadata)
.withSourcedId(TestData.RESULT_SOURCED_ID)
.withDate(LocalDateTime.now())
.withDateLastModified(LocalDateTime.now())
.withStatus(Status.active)
.withLineitem(new Link.Builder().withSourcedId(TestData.LINEITEM_SOURCED_ID).build())
.withStudent(new Link.Builder().withSourcedId(TestData.USER_SOURCED_ID).build())
.build();
HttpHeaders headers1 = getHeaders();
HttpEntity<Object> entity = new HttpEntity<Object>(result, headers1);
ResponseEntity<Result> responseEntity =
restTemplate.exchange(String.format("/api/classes/%s/results",sourcedId), HttpMethod.POST, entity, Result.class);
Result responseResult = responseEntity.getBody();
assertTrue(responseEntity.getStatusCode().is2xxSuccessful());
assertEquals(new Double(70.0), responseResult.getScore());
return responseEntity.getBody().getSourcedId();
}
示例6: IsOrderListReturned
import org.springframework.http.ResponseEntity; //导入方法依赖的package包/类
@Test
public void IsOrderListReturned() {
try {
Iterable<Order> orders = orderRepository.findAll();
assertTrue(StreamSupport.stream(orders.spliterator(), false)
.noneMatch(o -> ((o.getCustomer() != null) && (o.getCustomer().equals(customer)))));
ResponseEntity<String> resultEntity = restTemplate.getForEntity(orderURL(), String.class);
assertTrue(resultEntity.getStatusCode().is2xxSuccessful());
String orderList = resultEntity.getBody();
assertFalse(orderList.contains("RZA"));
Order order = new Order(customer);
order.addLine(42, item);
orderRepository.save(order);
orderList = restTemplate.getForObject(orderURL(), String.class);
assertTrue(orderList.contains("Eberhard"));
} finally {
orderRepository.deleteAll();
}
}
示例7: testPollNotificationWthPublicNamespaceAndDataCenter
import org.springframework.http.ResponseEntity; //导入方法依赖的package包/类
@Test(timeout = 5000L)
@Sql(scripts = "/integration-test/test-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testPollNotificationWthPublicNamespaceAndDataCenter() throws Exception {
String publicAppId = "somePublicAppId";
String someDC = "someDC";
AtomicBoolean stop = new AtomicBoolean();
periodicSendMessage(executorService, assembleKey(publicAppId, someDC, somePublicNamespace), stop);
ResponseEntity<ApolloConfigNotification> result = restTemplate
.getForEntity(
"{baseurl}/notifications?appId={appId}&cluster={clusterName}&namespace={namespace}&dataCenter={dataCenter}",
ApolloConfigNotification.class,
getHostUrl(), someAppId, someCluster, somePublicNamespace, someDC);
stop.set(true);
ApolloConfigNotification notification = result.getBody();
assertEquals(HttpStatus.OK, result.getStatusCode());
assertEquals(somePublicNamespace, notification.getNamespaceName());
assertNotEquals(0, notification.getNotificationId());
}
示例8: testQueryPublicConfigWithDataCenterFoundAndOverride
import org.springframework.http.ResponseEntity; //导入方法依赖的package包/类
@Test
@Sql(scripts = "/integration-test/test-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/test-release-public-dc-override.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testQueryPublicConfigWithDataCenterFoundAndOverride() throws Exception {
ResponseEntity<ApolloConfig> response = restTemplate
.getForEntity("{baseurl}/configs/{appId}/{clusterName}/{namespace}?dataCenter={dateCenter}",
ApolloConfig.class,
getHostUrl(), someAppId, someDefaultCluster, somePublicNamespace, someDC);
ApolloConfig result = response.getBody();
assertEquals(
"TEST-RELEASE-KEY6" + ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR + "TEST-RELEASE-KEY4",
result.getReleaseKey());
assertEquals(someAppId, result.getAppId());
assertEquals(someDC, result.getCluster());
assertEquals(somePublicNamespace, result.getNamespaceName());
assertEquals("override-someDC-v1", result.getConfigurations().get("k1"));
assertEquals("someDC-v2", result.getConfigurations().get("k2"));
}
示例9: should_return_cases_as_empty_list_if_patient_not_exist
import org.springframework.http.ResponseEntity; //导入方法依赖的package包/类
@Test
public void should_return_cases_as_empty_list_if_patient_not_exist() {
//Given
long patientId = 123123;
//When
ResponseEntity<List<Case>> response = testRestTemplate.
withBasicAuth("1","1").
exchange("/v1/cases?patientId="+patientId,
HttpMethod.GET,
null,
new ParameterizedTypeReference<List<Case>>() {
});
List<Case> cases = response.getBody();
//Then
assertThat(cases).isNotNull();
assertThat(cases).isEmpty();
}
示例10: getPrimaryEmail
import org.springframework.http.ResponseEntity; //导入方法依赖的package包/类
public GitHubEmail getPrimaryEmail(final String gitHubToken) {
RestTemplate template = new GitHubRestTemplate(gitHubToken);
ResponseEntity<List<GitHubEmail>> response = template.exchange(GITHUB_EMAIL_URL, HttpMethod.GET, null, new ParameterizedTypeReference<List<GitHubEmail>>(){});
List<GitHubEmail> emails = response.getBody();
GitHubEmail primary = emails.stream().filter(e -> e.isPrimary()).findFirst().get();
return primary;
}
示例11: _03_buscaAluno
import org.springframework.http.ResponseEntity; //导入方法依赖的package包/类
@Test
public void _03_buscaAluno() {
ResponseEntity<Aluno> response = restTemplate
.exchange(BASE_URI + "/"
+ alunoCriado.getCodigo(),
HttpMethod.GET, null, Aluno.class);
assertThat(response.getStatusCode())
.isEqualTo(HttpStatus.OK);
Aluno alunoBusca = response.getBody();
assertThat(alunoBusca.getCodigo()).isNotNull();
assertThat(alunoBusca.getCidade()).isEqualTo("Orleans");
}
示例12: extractData
import org.springframework.http.ResponseEntity; //导入方法依赖的package包/类
public <T> T extractData(ResponseEntity<HttpInputMessage> responseEntity, Class<T> returnType) {
// 本来应该有response数据为空的判断的,其实这里已经被前一步的restTemplate获取中判断过了,这里只用判断body为空即可
if (returnType == null || void.class == returnType || Void.class == returnType || responseEntity.getBody() == null) {
return null;
}
/* 先不管文件
if (WxWebUtils.isMutlipart(returnType)) {
return null;
}
不是不管文件,而是可以被messageConverter处理了
*/
WxApiMessageConverterExtractor<T> delegate = delegates.get(returnType);
if (delegate == null) {
delegate = new WxApiMessageConverterExtractor(returnType, converters);
delegates.put(returnType, delegate);
}
// 这里遇到了个坑,很长时间没玩过IO了,这个坑就和IO相关,每次提取数据时都抛出IO异常,IO已关闭
// 本来以为是我的error判断那里提前读了IO导致后来IO关闭了,调试后发现真正原因,因为
// ResponseEntity<HttpInputMessage> responseEntity = wxApiInvoker.exchange(requestEntity, HttpInputMessage.class);
// 上面代码执行结束后,有个finally,就是用于关闭response的,也就是说,一旦执行结束就无法再执行提取数据的操作了
// 所以我只能把WxHttpInputMessageConverter里返回的inputStream包装一下了
// 这里还涉及一个问题,是否有必要把所有消息都返回inputStream?当然没有必要,只要特定几种类型返回InputStream
// 其他类型直接转换即可。
try {
return delegate.extractData(responseEntity);
} catch (IOException e) {
logger.error(e.getMessage(), e);
throw new WxApiResponseException("提取数据时发生IO异常", responseEntity);
}
}
示例13: testPollNotificationWthPublicNamespaceAndNoDataCenter
import org.springframework.http.ResponseEntity; //导入方法依赖的package包/类
@Test(timeout = 5000L)
@Sql(scripts = "/integration-test/test-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testPollNotificationWthPublicNamespaceAndNoDataCenter() throws Exception {
String publicAppId = "somePublicAppId";
AtomicBoolean stop = new AtomicBoolean();
String key = assembleKey(publicAppId, ConfigConsts.CLUSTER_NAME_DEFAULT, somePublicNamespace);
periodicSendMessage(executorService, key, stop);
ResponseEntity<List<ApolloConfigNotification>> result = restTemplate.exchange(
"{baseurl}/notifications/v2?appId={appId}&cluster={clusterName}¬ifications={notifications}",
HttpMethod.GET, null, typeReference,
getHostUrl(), someAppId, someCluster,
transformApolloConfigNotificationsToString(somePublicNamespace, ConfigConsts.NOTIFICATION_ID_PLACEHOLDER));
stop.set(true);
List<ApolloConfigNotification> notifications = result.getBody();
assertEquals(HttpStatus.OK, result.getStatusCode());
assertEquals(1, notifications.size());
assertEquals(somePublicNamespace, notifications.get(0).getNamespaceName());
assertNotEquals(0, notifications.get(0).getNotificationId());
ApolloNotificationMessages messages = result.getBody().get(0).getMessages();
assertEquals(1, messages.getDetails().size());
assertTrue(messages.has(key));
assertNotEquals(ConfigConsts.NOTIFICATION_ID_PLACEHOLDER, messages.get(key).longValue());
}
示例14: save
import org.springframework.http.ResponseEntity; //导入方法依赖的package包/类
@Override
public EmailAlertsConfig save(BotConfig botConfig, EmailAlertsConfig emailAlertsConfig) {
try {
LOG.info(() -> "About to save EmailAlertsConfig: " + emailAlertsConfig);
restTemplate.getInterceptors().clear();
restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor(
botConfig.getUsername(), botConfig.getPassword()));
final String endpointUrl = botConfig.getBaseUrl() + EMAIL_ALERTS_RESOURCE_PATH;
LOG.info(() -> "Sending EmailAlertsConfig to: " + endpointUrl);
final HttpEntity<EmailAlertsConfig> requestUpdate = new HttpEntity<>(emailAlertsConfig);
final ResponseEntity<EmailAlertsConfig> savedConfig = restTemplate.exchange(
endpointUrl, HttpMethod.PUT, requestUpdate, EmailAlertsConfig.class);
LOG.info(() -> REMOTE_RESPONSE_RECEIVED_LOG_MSG + savedConfig);
final EmailAlertsConfig savedConfigBody = savedConfig.getBody();
savedConfigBody.setId(botConfig.getId());
return savedConfigBody;
} catch (RestClientException e) {
LOG.error(FAILED_TO_INVOKE_REMOTE_BOT_LOG_MSG + e.getMessage(), e);
return null;
}
}
示例15: jsonBodyOf
import org.springframework.http.ResponseEntity; //导入方法依赖的package包/类
private <T> T jsonBodyOf(ResponseEntity<String> entity, Class<T> aClass) {
try {
return RestObjectMapper.INSTANCE.readValue(entity.getBody(), aClass);
} catch (IOException e) {
throw new IllegalStateException("Failed to read JSON from response " + entity.getBody(), e);
}
}