当前位置: 首页>>代码示例>>Java>>正文


Java RestTemplate.exchange方法代码示例

本文整理汇总了Java中org.springframework.web.client.RestTemplate.exchange方法的典型用法代码示例。如果您正苦于以下问题:Java RestTemplate.exchange方法的具体用法?Java RestTemplate.exchange怎么用?Java RestTemplate.exchange使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.springframework.web.client.RestTemplate的用法示例。


在下文中一共展示了RestTemplate.exchange方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: getUserInfoFor

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
public Map<String, String> getUserInfoFor(OAuth2AccessToken accessToken) {
    RestTemplate restTemplate = new RestTemplate();

    RequestEntity<MultiValueMap<String, String>> requestEntity = new RequestEntity<>(
            getHeader(accessToken),
            HttpMethod.GET,
            URI.create("https://www.googleapis.com/oauth2/v3/userinfo")
    );

    ResponseEntity<Map> result = restTemplate.exchange(
            requestEntity, Map.class);

    if (result.getStatusCode().is2xxSuccessful()) {
        return result.getBody();
    }

    throw new RuntimeException("It wasn't possible to retrieve userInfo");
}
 
开发者ID:PacktPublishing,项目名称:OAuth-2.0-Cookbook,代码行数:19,代码来源:UserInfoService.java

示例2: getMarathonServiceDetails

import org.springframework.web.client.RestTemplate; //导入方法依赖的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

示例3: testLogin

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
@Test
public void testLogin() {
	try {
		String authUrl = String.format(AUTH_URL_BASE, port);
		JsonObject request = Json.createObjectBuilder()
				.add("id", DEFAULT_ID)
				.add("key", DEFAULT_KEY)
				.build();

		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);
		HttpEntity<String> entity = new HttpEntity<>(request.toString(), headers);
		RestTemplate rest = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
		ResponseEntity<String> response = rest.exchange(authUrl, HttpMethod.POST, entity, String.class);

		assertEquals(200, response.getStatusCodeValue());
		JsonReader reader = Json.createReader(new StringReader(response.getBody()));
		JsonObject o = reader.readObject();
		String token = o.getString("token");
		assertTrue(!StringUtils.isEmpty(token));
		logger.info(token);
	} catch (Exception e) {
		logger.error(e.getMessage(), e);
		fail(e.getMessage());
	}
}
 
开发者ID:kinota,项目名称:kinota-server,代码行数:27,代码来源:AgentLoginTest.java

示例4: confirmEmail

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
/**
 * This method activates the e-mail change using a token
 * @param token E-mail change activation token
 * @param uriComponentsBuilder {@link UriComponentsBuilder}
 * @return The ModelAndView for sign in
 */
@PreAuthorize("permitAll()")
@GetMapping(value = "changeEmail/thanks")
public
ModelAndView confirmEmail(
        @RequestParam final String token,
        final UriComponentsBuilder uriComponentsBuilder
) {
    SSLContextHelper.disable();

    final RestTemplate restTemplate = new RestTemplate();
    final HttpEntity<Object> entity = new HttpEntity<>(new HttpHeaders());

    final UriComponents uriComponents
            = uriComponentsBuilder.path("/api/v1.0/settings/changeEmail/token/{token}").buildAndExpand(token);

    ResponseEntity<Void> response;

    try {
        response = restTemplate
                .exchange(uriComponents.toUri(),
                          HttpMethod.PUT,
                          entity,
                          Void.class);
    } catch (HttpClientErrorException e) /* IF 404 */ {
        return new ModelAndView("tokenNotFound");
    }

    /* IF 200 */
    return new ModelAndView("redirect:/signIn");
}
 
开发者ID:JonkiPro,项目名称:REST-Web-Services,代码行数:37,代码来源:SettingsController.java

示例5: getAccessAndRefreshToken

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
public static CompositeAccessToken getAccessAndRefreshToken(String oauthEndpoint, String code, DashboardClient dashboardClient,
                                                      String redirectUri) throws RestClientException {
    String clientBasicAuth = getClientBasicAuthHeader(dashboardClient.getId(),  dashboardClient.getSecret());
    RestTemplate template = new RestTemplate();

    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.AUTHORIZATION, clientBasicAuth);
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    MultiValueMap<String,String> form = new LinkedMultiValueMap<>();
    form.add("response_type", "token");
    form.add("grant_type", "authorization_code");
    form.add("client_id", dashboardClient.getId());
    form.add("client_secret", dashboardClient.getSecret());
    form.add("redirect_uri", redirectUri);
    form.add("code", code);

    ResponseEntity<CompositeAccessToken> token = template.exchange(oauthEndpoint + "/token",
            HttpMethod.POST, new HttpEntity<>(form, headers), CompositeAccessToken.class);

    if (token != null)
        return token.getBody();
    else
        return null;
}
 
开发者ID:evoila,项目名称:cfsummiteu2017,代码行数:26,代码来源:OpenIdAuthenticationUtils.java

示例6: main

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
public static void main(String[] args) throws Exception {
  RestTemplate template = new RestTemplate();
  template.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
  MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
  headers.add("X-Tenant-Name", "default");

  RequestEntity<String> requestEntity = new RequestEntity<String>(headers, HttpMethod.GET,
      new URI("http://127.0.0.1:9980/registry/v3/microservices"));
  ResponseEntity<String> stringResponseEntity = template.exchange(requestEntity, String.class);
  System.out.println(stringResponseEntity.getBody());
  ResponseEntity<MicroserviceArray> microseriveResponseEntity = template
      .exchange(requestEntity, MicroserviceArray.class);
  MicroserviceArray microserives = microseriveResponseEntity.getBody();
  System.out.println(microserives.getServices().get(1).getServiceId());

  // instance
  headers.add("X-ConsumerId", microserives.getServices().get(1).getServiceId());
  requestEntity = new RequestEntity<String>(headers, HttpMethod.GET,
      new URI("http://127.0.0.1:9980/registry/v3/microservices/" + microserives.getServices().get(1).getServiceId()
          + "/instances"));
  ResponseEntity<String> microserviceInstanceResponseEntity = template.exchange(requestEntity, String.class);
  System.out.println(microserviceInstanceResponseEntity.getBody());
}
 
开发者ID:apache,项目名称:incubator-servicecomb-java-chassis,代码行数:24,代码来源:ServiceCenterExample.java

示例7: getPrimaryEmail

import org.springframework.web.client.RestTemplate; //导入方法依赖的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

示例8: getWorkspaceStatus

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
/**
 * Gets workspace status
 * 
 * @param cheServerURL
 *            Che server URL
 * @param workspaceId
 *            workspace ID
 * @return workspace status
 */
public WorkspaceStatus getWorkspaceStatus(String cheServerURL, String workspaceId, String keycloakToken) {
    String url = CheRestEndpoints.CHECK_WORKSPACE.generateUrl(cheServerURL, workspaceId);

    RestTemplate template = new KeycloakRestTemplate(keycloakToken);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<String> entity = new HttpEntity<String>(headers);

    ResponseEntity<WorkspaceStatus> status = template.exchange(url, HttpMethod.GET, entity, WorkspaceStatus.class);
    return status.getBody();
}
 
开发者ID:redhat-developer,项目名称:che-starter,代码行数:21,代码来源:WorkspaceClient.java

示例9: findById

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
@Override
public Map<String, Object> findById(SelectionSet selections, Map<String, String> id, String authHeader) {

    String queryToRun = buildSelectionQuery(selections, id);

    RestTemplate schemaRetriever = new RestTemplate();
    HttpEntity<String> entity = buildEntity(authHeader);
    Map<String, String> variables = buildVariables(queryToRun);

    ResponseEntity<String> response = schemaRetriever.exchange(baseURLTemplate + PARAM_TEMPLATE,
            HttpMethod.GET, entity, String.class, variables);
    if (response.getStatusCode().equals(HttpStatus.OK)) {
        String jsonRaw = response.getBody();
        try {
            @SuppressWarnings("unchecked")
            Map<String, Object> retMap = objectMapper.readValue(jsonRaw, Map.class);
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> itemList = (List<Map<String, Object>>)
                    ((Map<String, Object>) ((Map<String, Object>) retMap.get("data")).get("viewer")).get("nodes");
            if (itemList.isEmpty()) {
                return null;
            } else {
                return itemList.get(0);
            }
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);          }
    }

    throw new RuntimeException("Schema retrieve failed: " + response.getStatusCode() + " body: " + response.getBody());
}
 
开发者ID:nfl,项目名称:gold,代码行数:31,代码来源:ExternalReferenceRepositoryImpl.java

示例10: execute

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
public String execute(YadaFacebookRequest yadaFacebookRequest) throws YadaSocialException {
	try {
		RestTemplate restTemplate = new RestTemplate();
		String url = yadaFacebookRequest.getUrl();
		ResponseEntity<String> responseEntity = restTemplate.exchange(url, yadaFacebookRequest.getHttpMethod(), null, String.class);
		String body = responseEntity.getBody();
		yadaFacebookRequest.checkForErrors(body);
		return body;
	} catch (Exception e) {
		throw new YadaSocialException(e);
	}
}
 
开发者ID:xtianus,项目名称:yadaframework,代码行数:13,代码来源:YadaSocial.java

示例11: should_return_duke

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
@Test
public void should_return_duke() throws Exception {
    // given
    LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
    ClassPathResource dukeResource = new ClassPathResource("Duke-Istanbul.png");
    map.add("file", dukeResource);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);

    // when
    ResponseEntity<Media> result = testRestTemplate
            .withBasicAuth("1", "1")
            .exchange("/v1/media",
                    HttpMethod.POST,
                    new HttpEntity<>(map, headers),
                    Media.class);

    // then
    RestTemplate restTemplate = getRawRestTemplate();

    ResponseEntity<byte[]> responseEntity = restTemplate
            .exchange(result.getBody().getUrl(),
                    HttpMethod.GET,
                    HttpEntity.EMPTY,
                    byte[].class);

    assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK);
    assertThat(responseEntity.getBody()).isEqualTo(readAllBytes(get(dukeResource.getURI())));

}
 
开发者ID:JUGIstanbul,项目名称:second-opinion-api,代码行数:31,代码来源:MediaDownloadControllerIT.java

示例12: getContributorsByCommitsDesc

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
public static List<Stat.Author> getContributorsByCommitsDesc() throws IOException {
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<Stat[]> exchange = restTemplate.
            exchange("https://api.github.com/repos/"
                    + githubUsername + "/" + githubReponame + "/stats/contributors", HttpMethod.GET, null, Stat[].class);
    Stat[] stats = exchange.getBody();
    List<Stat.Author> contributors = new ArrayList<>(stats.length);
    for (Stat s : stats) {
        Stat.Author author = s.getAuthor();
        author.setCommits(s.getTotal());
        contributors.add(0, author);
    }
    return contributors;
}
 
开发者ID:Code4SocialGood,项目名称:c4sg-services,代码行数:15,代码来源:GithubUtil.java

示例13: getPolicySet

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
private PolicySet getPolicySet(final RestTemplate acs, final String policyName, final HttpHeaders headers,
        final String acsEndpointParam) {
    ResponseEntity<PolicySet> policySetResponse = acs.exchange(
            acsEndpointParam + PolicyHelper.ACS_POLICY_SET_API_PATH + policyName, HttpMethod.GET,
            new HttpEntity<>(headers), PolicySet.class);
    return policySetResponse.getBody();
}
 
开发者ID:eclipse,项目名称:keti,代码行数:8,代码来源:AccessControlServiceIT.java

示例14: testSecureService

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
@Test
public void testSecureService() {	
	String plainCreds = "guest:guest123";
	HttpHeaders headers = new HttpHeaders();
	headers.add("Authorization", "Basic " + new String(Base64.encode(plainCreds.getBytes())));
	HttpEntity<String> request = new HttpEntity<String>(headers);
	RestTemplate restTemplate = new RestTemplate();
	
	ResponseEntity<Greet> response = restTemplate.exchange("http://localhost:8080", HttpMethod.GET, request, Greet.class);
	Assert.assertEquals("Hello World!", response.getBody().getMessage());
}
 
开发者ID:rajeshrv,项目名称:SpringMicroservice,代码行数:12,代码来源:ApplicationTests.java

示例15: deletePolicySet

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
public void deletePolicySet(final RestTemplate restTemplate, final String acsUrl, final String testPolicyName,
        final HttpHeaders headers) {
    if (testPolicyName != null) {
        restTemplate.exchange(acsUrl + ACS_POLICY_SET_API_PATH + testPolicyName, HttpMethod.DELETE,
                new HttpEntity<>(headers), String.class);
    }
}
 
开发者ID:eclipse,项目名称:keti,代码行数:8,代码来源:PolicyHelper.java


注:本文中的org.springframework.web.client.RestTemplate.exchange方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。