當前位置: 首頁>>代碼示例>>Java>>正文


Java ResponseEntity.getBody方法代碼示例

本文整理匯總了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");
}
 
開發者ID:PacktPublishing,項目名稱:OAuth-2.0-Cookbook,代碼行數:21,代碼來源:UserInfoService.java

示例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();
}
 
開發者ID:PacktPublishing,項目名稱:Learning-Spring-Boot-2.0-Second-Edition,代碼行數:18,代碼來源:CommentHelper.java

示例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;
    }
}
 
開發者ID:HewlettPackard,項目名稱:loom,代碼行數:29,代碼來源:BaseApi.java

示例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;
    }
}
 
開發者ID:dcos-utilities,項目名稱:f5-marathon-autoscale,代碼行數:22,代碼來源:MarathonGateway.java

示例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();
}
 
開發者ID:Apereo-Learning-Analytics-Initiative,項目名稱:OpenLRW,代碼行數:26,代碼來源:IntegrationAPITest.java

示例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();
	}
}
 
開發者ID:ewolff,項目名稱:microservice-kafka,代碼行數:20,代碼來源:OrderWebIntegrationTest.java

示例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());
}
 
開發者ID:dewey-its,項目名稱:apollo-custom,代碼行數:24,代碼來源:NotificationControllerIntegrationTest.java

示例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"));
}
 
開發者ID:dewey-its,項目名稱:apollo-custom,代碼行數:21,代碼來源:ConfigControllerIntegrationTest.java

示例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();
}
 
開發者ID:JUGIstanbul,項目名稱:second-opinion-api,代碼行數:20,代碼來源:CaseControllerIT.java

示例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;
}
 
開發者ID:redhat-developer,項目名稱:che-starter,代碼行數:8,代碼來源:GitHubClient.java

示例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");
}
 
開發者ID:panga,項目名稱:unibave-backend,代碼行數:13,代碼來源:AlunoResourceTest.java

示例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);
    }
}
 
開發者ID:FastBootWeixin,項目名稱:FastBootWeixin,代碼行數:31,代碼來源:WxApiResponseExtractor.java

示例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}&notifications={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());
}
 
開發者ID:dewey-its,項目名稱:apollo-custom,代碼行數:30,代碼來源:NotificationControllerV2IntegrationTest.java

示例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;
    }
}
 
開發者ID:gazbert,項目名稱:bxbot-ui-server,代碼行數:28,代碼來源:EmailAlertsConfigRepositoryRestClient.java

示例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);
  }
}
 
開發者ID:apache,項目名稱:incubator-servicecomb-java-chassis,代碼行數:8,代碼來源:JaxrsIntegrationTestBase.java


注:本文中的org.springframework.http.ResponseEntity.getBody方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。