Java 类org.springframework.web.client.RestTemplate 实例源码

项目:twitch4j    文件:TMIEndpoint.java   
/**
 * Gets all user's present in the twitch chat of a channel.
 *
 * @param channelName Channel to fetch the information for.
 * @return All chatters in a channel, separated into groups like admins, moderators and viewers.
 */
public Chatter getChatters(String channelName) {
    // Endpoint
    String requestUrl = String.format("%s/group/user/%s/chatters", Endpoints.TMI.getURL(), channelName);
    RestTemplate restTemplate = getTwitchClient().getRestClient().getRestTemplate();

    // REST Request
    try {
        if (!restObjectCache.containsKey(requestUrl)) {
            Logger.trace(this, "Rest Request to [%s]", requestUrl);
            ChatterResult responseObject = restTemplate.getForObject(requestUrl, ChatterResult.class);
            restObjectCache.put(requestUrl, responseObject, ExpirationPolicy.CREATED, 60, TimeUnit.SECONDS);
        }

        return ((ChatterResult) restObjectCache.get(requestUrl)).getChatters();

    } catch (RestException restException) {
        Logger.error(this, "RestException: " + restException.getRestError().toString());
    } catch (Exception ex) {
        Logger.error(this, "Request failed: " + ex.getMessage());
        Logger.trace(this, ExceptionUtils.getStackTrace(ex));
    }

    // OnError: Return empty result
    return new Chatter();
}
项目:websocket-poc    文件:App.java   
@Bean
public RestTemplate restTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {

    SSLContext sslContext = SSLContexts.custom()
            .loadTrustMaterial(null, new TrustSelfSignedStrategy())
            .build();

    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
    CloseableHttpClient httpClient = HttpClients.custom()
            .setSSLSocketFactory(sslConnectionSocketFactory)
            .build();

    HttpComponentsClientHttpRequestFactory requestFactory =
            new HttpComponentsClientHttpRequestFactory();

    requestFactory.setHttpClient(httpClient);

    return new RestTemplate(requestFactory);
}
项目:incubator-servicecomb-java-chassis    文件:JaxrsClient.java   
private static void testExchange(RestTemplate template, String cseUrlPrefix) {
  HttpHeaders headers = new HttpHeaders();
  headers.add("Accept", MediaType.APPLICATION_JSON);
  Person person = new Person();
  person.setName("world");
  HttpEntity<Person> requestEntity = new HttpEntity<>(person, headers);
  ResponseEntity<Person> resEntity = template.exchange(cseUrlPrefix + "/compute/sayhello",
      HttpMethod.POST,
      requestEntity,
      Person.class);
  TestMgr.check("hello world", resEntity.getBody());

  ResponseEntity<String> resEntity2 =
      template.exchange(cseUrlPrefix + "/compute/addstring?s=abc&s=def", HttpMethod.DELETE, null, String.class);
  TestMgr.check("abcdef", resEntity2.getBody());
}
项目:twitch4j    文件:StreamEndpoint.java   
/**
 * Get Featured Streams
 * <p>
 * Gets a list of all featured live streams.
 * Requires Scope: none
 *
 * @param limit  Maximum number of most-recent objects to return. Default: 25. Maximum: 100.
 * @param offset Object offset for pagination of results. Default: 0.
 * @return The requested range/amount of featured streams.
 */
public List<StreamFeatured> getFeatured(Optional<Long> limit, Optional<Long> offset) {
    // Endpoint
    String requestUrl = String.format("%s/streams/featured", Endpoints.API.getURL());
    RestTemplate restTemplate = getTwitchClient().getRestClient().getRestTemplate();

    // Parameters
    restTemplate.getInterceptors().add(new QueryRequestInterceptor("limit", limit.orElse(25l).toString()));
    restTemplate.getInterceptors().add(new QueryRequestInterceptor("offset", offset.orElse(0l).toString()));

    // REST Request
    try {
        StreamFeaturedList responseObject = restTemplate.getForObject(requestUrl, StreamFeaturedList.class);

        return responseObject.getFeatured();
    } catch (Exception ex) {
        Logger.error(this, "Request failed: " + ex.getMessage());
        Logger.trace(this, ExceptionUtils.getStackTrace(ex));
    }

    return new ArrayList<StreamFeatured>();
}
项目:waggle-dance    文件:WaggleDanceIntegrationTest.java   
@Test
public void restApiGetStatus() throws Exception {
  exit.expectSystemExitWithStatus(0);

  runner = WaggleDanceRunner
      .builder(configLocation)
      .primary("primary", localServer.getThriftConnectionUri(), READ_ONLY)
      .federate("waggle_remote", remoteServer.getThriftConnectionUri(), REMOTE_DATABASE)
      .build();

  runWaggleDance(runner);

  RestTemplate rest = new RestTemplateBuilder().build();
  PrimaryMetaStore primaryMetastore = rest.getForObject("http://localhost:18000/api/admin/federations/primary",
      PrimaryMetaStore.class);
  assertThat(primaryMetastore.getStatus(), is(MetaStoreStatus.AVAILABLE));
  FederatedMetaStore federatedMetastore = rest
      .getForObject("http://localhost:18000/api/admin/federations/waggle_remote", FederatedMetaStore.class);
  assertThat(federatedMetastore.getStatus(), is(MetaStoreStatus.AVAILABLE));
}
项目:java-spring-web    文件:TracingRestTemplateTest.java   
public TracingRestTemplateTest() {
    final RestTemplate restTemplate = new RestTemplate();
    restTemplate.setInterceptors(Collections.<ClientHttpRequestInterceptor>singletonList(
            new TracingRestTemplateInterceptor(mockTracer)));

    client = new Client<RestTemplate>() {
        @Override
        public <T> ResponseEntity<T> getForEntity(String url, Class<T> clazz) {
            return restTemplate.getForEntity(url, clazz);
        }

        @Override
        public RestTemplate template() {
            return restTemplate;
        }
    };

    mockServer = MockRestServiceServer.bindTo(client.template()).build();
}
项目:xitikit-blue    文件:SimpleB2CAuthenticationService.java   
public SimpleB2CAuthenticationService(
  final ClaimValidationService claimValidationService,
  final NonceService nonceService,
  final UrlService urlService,
  final RestTemplate restTemplate){

    Assert.notNull(
      claimValidationService,
      "Missing required parameter 'claimValidationService' " +
        "(org.xitikit.blue.noitacitnehtua.api.v2dot0.SimpleB2CAuthenticationService::new)");
    Assert.notNull(nonceService, "Missing required parameter 'nonceService' (org.xitikit.blue.noitacitnehtua.api.v2dot0.SimpleB2CAuthenticationService::new)");
    Assert.notNull(urlService, "Missing required parameter 'blueUrlService' (org.xitikit.blue.noitacitnehtua.api.v2dot0.SimpleB2CAuthenticationService::new)");
    Assert.notNull(restTemplate, "Missing required parameter 'restTemplate' (org.xitikit.blue.noitacitnehtua.api.v2dot0.SimpleB2CAuthenticationService::new)");

    this.claimValidationService = claimValidationService;
    this.nonceService = nonceService;
    this.urlService = urlService;
    this.restTemplate = restTemplate;
}
项目:twitch4j    文件:StreamEndpoint.java   
/**
 * Get Followed Streams
 * <p>
 * Gets the list of online streams a user follows based on the OAuthTwitch token provided.
 * Requires Scope: user_read
 *
 * @param credential The user.
 * @return All streams as user follows.
 */
public List<Stream> getFollowed(OAuthCredential credential) {
    // Endpoint
    String requestUrl = String.format("%s/streams/followed", Endpoints.API.getURL());
    RestTemplate restTemplate = getTwitchClient().getRestClient().getPrivilegedRestTemplate(credential);

    // REST Request
    try {
        StreamList responseObject = restTemplate.getForObject(requestUrl, StreamList.class);

        return responseObject.getStreams();
    } catch (Exception ex) {
        Logger.error(this, "Request failed: " + ex.getMessage());
        Logger.trace(this, ExceptionUtils.getStackTrace(ex));
    }

    return new ArrayList<Stream>();
}
项目:esup-ecandidat    文件:LimeSurveyRest.java   
/** Execute un WS sur LimeSurvey
 * @param obj
 * @return la ResponseEntity
 */
private ResponseEntity<String> executeWS(LimeSurveyRestObject obj){
    try {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);                     
        String serialized;
        ObjectMapper mapper = new ObjectMapper();
        serialized = mapper.writeValueAsString(obj);
        HttpEntity<String> requestEntity=new HttpEntity<String>(serialized,headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.exchange(URL,HttpMethod.POST,requestEntity,String.class);
        return response;
    } catch (Exception e) {
        logger.error("Erreur d'appel du web service "+obj.getMethod()+" sur LimeSurvey",e);
        return null;
    }
}
项目:twitch4j    文件:UserEndpoint.java   
/**
 * Endpoint to get the UserId from the UserName
 * <p>
 * https://api.twitch.tv/kraken/users?login=USERNAME
 *
 * @param userName todo
 * @return todo
 */
public Optional<Long> getUserIdByUserName(String userName) {
    // Validate Arguments
    Assert.hasLength(userName, "Please provide a Username!");

    // REST Request
    String requestUrl = String.format("%s/users?login=%s", Endpoints.API.getURL(), userName);
    RestTemplate restTemplate = getTwitchClient().getRestClient().getRestTemplate();

    // REST Request
    if (!restObjectCache.containsKey(requestUrl)) {
        try {
            UserList responseObject = restTemplate.getForObject(requestUrl, UserList.class);
            restObjectCache.put(requestUrl, responseObject, 15, TimeUnit.MINUTES);
        } catch (RestException restException) {
            Logger.error(this, "RestException: " + restException.getRestError().toString());
        } catch (Exception ex) {
            Logger.error(this, "Request failed: " + ex.getMessage());
            Logger.trace(this, ExceptionUtils.getStackTrace(ex));
            return Optional.empty();
        }
    }

    List<User> userList = ((UserList) restObjectCache.get(requestUrl)).getUsers();

    // User found?
    if (userList.size() == 1) {
        return Optional.ofNullable(userList.get(0).getId());
    } else {
        return Optional.empty();
    }
}
项目:twitch4j    文件:KrakenEndpoint.java   
/**
 * Endpoint: Get OAuth Token Information
 * Gets information about the provided oAuthToken
 * Requires Scope: none
 *
 * @param credential The credential the information should be fetched for.
 * @return Information about the user, that issued the token - also provides info about scopes/valid/etc.
 * @see Token
 */
public Token getToken(OAuthCredential credential) {
    // Endpoint
    String requestUrl = String.format("%s", Endpoints.API.getURL());
    RestTemplate restTemplate = getTwitchClient().getRestClient().getPrivilegedRestTemplate(credential);

    // REST Request
    try {
        TokenResponse responseObject = restTemplate.getForObject(requestUrl, TokenResponse.class);

        return responseObject.getToken();
    } catch (RestException restException) {
        Logger.error(this, "RestException: " + restException.getRestError().toString());
    } catch (Exception ex) {
        Logger.error(this, "Request failed: " + ex.getMessage());
        Logger.trace(this, ExceptionUtils.getStackTrace(ex));
    }

    // Default Response: Invalid Token
    return new Token();
}
项目:shoucang    文件:MailService.java   
public void sendViaMailgunApi(EmailParams emailParams) {
    String apiUrl = jHipsterProperties.getMailgun().getApiUrl();
    String apiKey = jHipsterProperties.getMailgun().getApiKey();

    MultiValueMap<String, Object> vars = new LinkedMultiValueMap<>();
    vars.add("from", jHipsterProperties.getMailgun().getFrom());
    vars.add("to", emailParams.getTo());
    vars.add("subject", emailParams.getSubject());
    vars.add("html", emailParams.getContent());

    RestTemplate restTemplate = new BasicAuthRestTemplate(MAILGUN_USER_NAME, apiKey);
    restTemplate.postForLocation(apiUrl, vars);

    log.debug("Email sent successfully.");
}
项目:csap-core    文件:HttpCollector.java   
private RestTemplate getRestTemplate ( long maxConnectionInMs, JsonNode user, JsonNode pass, String desc ) {

        logger.debug( "maxConnectionInMs: {} , user: {} , Pass: {} ", maxConnectionInMs, user, pass );

        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();

        // "user" : "$csapUser1", "pass" : "$csapPass1"
        if ( user != null && pass != null ) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(
                new AuthScope( null, -1 ),
                new UsernamePasswordCredentials(
                    user.asText(),
                    csapApplication.decode( pass.asText(), desc ) ) );

            HttpClient httpClient = HttpClients
                .custom()
                .setDefaultCredentialsProvider( credsProvider )
                .build();
            factory.setHttpClient( httpClient );
            // factory = new HttpComponentsClientHttpRequestFactory(httpClient);
        }

        factory.setConnectTimeout( (int) maxConnectionInMs );
        factory.setReadTimeout( (int) maxConnectionInMs );

        RestTemplate restTemplate = new RestTemplate( factory );

        return restTemplate;
    }
项目:loom    文件:SwiftContainersImpl.java   
private List<JsonContainer> getMore(final RestTemplate rt, final String url, final JsonContainer last)
        throws URISyntaxException, UnsupportedEncodingException {
    String params = url.contains("?") ? "&" : "?";
    String newUrl = url + params + "marker=" + URLEncoder.encode(last.getName(), "UTF-8");
    URI keystoneURI = new URI(newUrl);
    JsonContainer[] data = getResourcesFromGet(rt, keystoneURI);
    List<JsonContainer> list = new ArrayList<>();
    list.addAll(Arrays.asList(data));
    if (data.length != 0) {
        // check for more
        List<JsonContainer> extra = getMore(rt, url, data[data.length - 1]);
        list.addAll(extra);
    }
    return list;
}
项目:spring-cloud-skipper    文件:DefaultSkipperClientTests.java   
@Test
public void testStatusReleaseNameFound() {
    RestTemplate restTemplate = new RestTemplate();
    SkipperClient skipperClient = new DefaultSkipperClient("", restTemplate);

    MockRestServiceServer mockServer = MockRestServiceServer.bindTo(restTemplate).build();
    mockServer.expect(requestTo("/release/status/mylog")).andRespond(withSuccess("{}", MediaType.APPLICATION_JSON));

    Info status = skipperClient.status("mylog");
    mockServer.verify();

    assertThat(status).isNotNull();
    assertThat(status).isInstanceOf(Info.class);
}
项目:keti    文件:AccessControlServiceIT.java   
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();
}
项目:incubator-servicecomb-java-chassis    文件:RestTemplateWrapper.java   
RestTemplate getRestTemplate(String url) {
  for (AcceptableRestTemplate template : acceptableRestTemplates) {
    if (template.isAcceptable(url)) {
      return template;
    }
  }
  return defaultRestTemplate;
}
项目:incubator-servicecomb-java-chassis    文件:CodeFirstRestTemplateSpringmvc.java   
private void testUpload(RestTemplate template, String cseUrlPrefix) throws IOException {
  String file1Content = "hello world";
  File file1 = File.createTempFile("upload1", ".txt");
  FileUtils.writeStringToFile(file1, file1Content);

  String file2Content = " bonjour";
  File someFile = File.createTempFile("upload2", ".txt");
  FileUtils.writeStringToFile(someFile, file2Content);

  String expect = String.format("%s:%s:%s\n"
      + "%s:%s:%s",
      file1.getName(),
      MediaType.TEXT_PLAIN_VALUE,
      file1Content,
      someFile.getName(),
      MediaType.TEXT_PLAIN_VALUE,
      file2Content);

  String result = testRestTemplateUpload(template, cseUrlPrefix, file1, someFile);
  TestMgr.check(expect, result);

  result = uploadPartAndFile.fileUpload(new FilePart(null, file1), someFile);
  TestMgr.check(expect, result);

  expect = String.format("null:%s:%s\n"
      + "%s:%s:%s",
      MediaType.APPLICATION_OCTET_STREAM_VALUE,
      file1Content,
      someFile.getName(),
      MediaType.TEXT_PLAIN_VALUE,
      file2Content);
  result = uploadStreamAndResource
      .fileUpload(new ByteArrayInputStream(file1Content.getBytes(StandardCharsets.UTF_8)),
          new PathResource(someFile.getAbsolutePath()));
  TestMgr.check(expect, result);
}
项目:poppynotes    文件:TestConfig.java   
@Primary
@Bean(name="testRestTemplate")
RestTemplate restTemplate() {
    RestTemplate template = new RestTemplate();
    template.setErrorHandler(getResponseErrorHandler());

    return template;
}
项目:spring-cloud-master    文件:TestController.java   
/**
 * 采用 RestTemplate 方式调用(HTTP方式调用,与 Spring Cloud 调用服务没有一点关系)
 * 
 * @param name
 * @return
 */
@RequestMapping(value = "callByHttpUrl", method = RequestMethod.GET)
public String callByHttpUrl(String name) {
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:8001/sayHello?name=" + name,
            String.class);
    return response.getBody();
}
项目:resilient-transport-service    文件:AddressCommand.java   
public AddressCommand(AddressDTO addressDTO, RestTemplate restTemplate, boolean secondTry) {
    super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("AddressServiceClientGroup"))
        .andCommandKey(HystrixCommandKey.Factory.asKey("AddressServiceClient")));

    this.addressDTO = addressDTO;
    this.restTemplate = restTemplate;
    this.secondTry = secondTry;
}
项目:loom    文件:NeutronNetworksImpl.java   
@Override
public JsonNetworks createNetworks(final JsonNetworks networks) {
    String url = getUri();
    RestTemplate rt = getRestTemplate(jsonEndpoint.getProjectId());
    ResponseEntity<JsonNetworks> result = rt.postForEntity(url, networks, JsonNetworks.class);

    return result.getBody();
}
项目:cas-5.1.0    文件:RestMultifactorAuthenticationTrustStorage.java   
@Override
protected MultifactorAuthenticationTrustRecord setInternal(final MultifactorAuthenticationTrustRecord record) {
    final RestTemplate restTemplate = new RestTemplate();
    final ResponseEntity<Object> response = restTemplate.postForEntity(this.endpoint, record, Object.class);
    if (response != null && response.getStatusCode() == HttpStatus.OK) {
        return record;
    }
    return null;
}
项目:mirrorgate-jira-stories-collector    文件:Config.java   
@Bean(MIRRORGATE_REST_TEMPLATE)
public RestTemplate getRestTemplate() {
    RestTemplate restTemplate = new RestTemplate();
    MappingJackson2HttpMessageConverter jsonHttpMessageConverter = new MappingJackson2HttpMessageConverter();
    restTemplate.getMessageConverters().add(jsonHttpMessageConverter);
    if(mirrorGateUserName.isPresent() && !mirrorGateUserName.get().isEmpty()) {
        restTemplate.getInterceptors().add(
                new BasicAuthorizationInterceptor(mirrorGateUserName.get(), mirrorGatePassword.get()));
    }

    return restTemplate;
}
项目:twitch4j    文件:ChannelEndpoint.java   
/**
 * Endpoint: Get Channel Editors
 * Gets a list of users who are editors for a specified channel.
 * Requires Scope: channel_read
 *
 * @return todo
 */
public List<User> getEditors() {
    // Check Scope
    Optional<OAuthCredential> twitchCredential = getTwitchClient().getCredentialManager().getTwitchCredentialsForChannel(getChannelId());
    if (twitchCredential.isPresent()) {
        Set<String> requiredScopes = new HashSet<String>();
        requiredScopes.add(TwitchScopes.CHANNEL_READ.getKey());

        checkScopePermission(twitchCredential.get().getOAuthScopes(), requiredScopes);
    } else {
        throw new ChannelCredentialMissingException(getChannelId());
    }

    // Endpoint
    String requestUrl = String.format("%s/channels/%s/editors", Endpoints.API.getURL(), getChannelId());
    RestTemplate restTemplate = getTwitchClient().getRestClient().getRestTemplate();

    // REST Request
    try {
        UserList responseObject = restTemplate.getForObject(requestUrl, UserList.class);

        return responseObject.getUsers();
    } catch (Exception ex) {
        Logger.error(this, "Request failed: " + ex.getMessage());
        Logger.trace(this, ExceptionUtils.getStackTrace(ex));
        return null;
    }
}
项目:java-spring-web    文件:AbstractTracingClientTest.java   
@Test
public void testErrorUnknownHostException() {
    String url = "http://nonexisting.example.com";
    try {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setInterceptors(Collections.<ClientHttpRequestInterceptor>singletonList(
                new TracingRestTemplateInterceptor(mockTracer)));
        restTemplate.getForEntity(url, String.class);
    } catch (ResourceAccessException ex) {
        //ok UnknownHostException
    }

    List<MockSpan> mockSpans = mockTracer.finishedSpans();
    Assert.assertEquals(1, mockSpans.size());

    MockSpan mockSpan = mockSpans.get(0);
    Assert.assertEquals("GET", mockSpan.operationName());
    Assert.assertEquals(5, mockSpan.tags().size());
    Assert.assertEquals(RestTemplateSpanDecorator.StandardTags.COMPONENT_NAME,
            mockSpan.tags().get(Tags.COMPONENT.getKey()));
    Assert.assertEquals(Tags.SPAN_KIND_CLIENT, mockSpan.tags().get(Tags.SPAN_KIND.getKey()));
    Assert.assertEquals("GET", mockSpan.tags().get(Tags.HTTP_METHOD.getKey()));
    Assert.assertEquals(url, mockSpan.tags().get(Tags.HTTP_URL.getKey()));
    Assert.assertEquals(Boolean.TRUE, mockSpan.tags().get(Tags.ERROR.getKey()));

    Assert.assertEquals(1, mockSpan.logEntries().size());
    Assert.assertEquals(2, mockSpan.logEntries().get(0).fields().size());
    Assert.assertEquals(Tags.ERROR.getKey(), mockSpan.logEntries().get(0).fields().get("event"));
    Assert.assertNotNull(mockSpan.logEntries().get(0).fields().get("error.object"));
}
项目:referenceapp    文件:ApplicationTests.java   
@Test
public void loginSucceeds() {
    RestTemplate template = new TestRestTemplate("user", "foo");
    ResponseEntity<String> response = template.getForEntity("http://localhost:" + port
            + "/user", String.class);
    assertEquals(HttpStatus.OK, response.getStatusCode());
}
项目:c4sg-services    文件:GithubUtil.java   
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;
}
项目:xitikit-blue    文件:AzureGraphApiClient.java   
public AzureGraphApiClient(
    final RestTemplate restTemplate,
    final IAzureCustomAttributeCacheService azureCustomAttributeCacheService,
    final GraphApiClientProperties graphApiClientProperties){

    this.restTemplate = restTemplate;
    this.azureCustomAttributeCacheService = azureCustomAttributeCacheService;
    this.graphApiClientProperties = graphApiClientProperties;
}
项目:xm-uaa    文件:TwitterTemplate.java   
@Override
public RestTemplate getRestTemplate() {
    if (clientRestTemplate != null) {
        return clientRestTemplate;
    }
    return super.getRestTemplate();
}
项目:loom    文件:PagingBase.java   
protected void processNext(final R result, final RestTemplate rt) {
    String nextUrl = getNext(result);
    if (nextUrl != null) {
        R nextResults = getJsonResources(rt, nextUrl);
        addToResult(result, nextResults);
    }
}
项目:amazon-ecs-java-microservices    文件:OwnerController.java   
private List<Visit> getPetVisits(int petId){
    List<Visit> visitList = new ArrayList<Visit>();
    RestTemplate restTemplate = new RestTemplate();
    Pet pet = restTemplate.getForObject("http://"+serviceEndpoint+"/pet/"+petId, Pet.class);
    logger.info(pet.getVisits().toString());
    return pet.getVisits();
}
项目:crnk-framework    文件:BasicSpringBootTest.java   
@Test
public void testTestCustomEndpoint() {
    RestTemplate testRestTemplate = new RestTemplate();
    ResponseEntity<String> response = testRestTemplate
            .getForEntity("http://localhost:" + this.port + "/api/custom", String.class);
    assertEquals(HttpStatus.OK, response.getStatusCode());
    assertEquals(response.getBody(), "hello");
}
项目:microservice-cloudfoundry    文件:CustomerClient.java   
public boolean isValidCustomerId(long customerId) {
    RestTemplate restTemplate = new RestTemplate();
    try {
        ResponseEntity<String> entity = restTemplate.getForEntity(customerURL() + customerId, String.class);
        return entity.getStatusCode().is2xxSuccessful();
    } catch (final HttpClientErrorException e) {
        if (e.getStatusCode().value() == 404)
            return false;
        else
            throw e;
    }
}
项目:cas-5.1.0    文件:RestGoogleAuthenticatorTokenCredentialRepository.java   
public RestGoogleAuthenticatorTokenCredentialRepository(final IGoogleAuthenticator googleAuthenticator,
                                                        final RestTemplate restTemplate,
                                                        final MultifactorAuthenticationProperties.GAuth gauth) {
    this.googleAuthenticator = googleAuthenticator;
    this.restTemplate = restTemplate;
    this.gauth = gauth;
}
项目:spring-cloud-master    文件:RetryApplication.java   
@Bean
@LoadBalanced // 自动负载均衡:他的机制是(通过)Application Name去寻找服务发现,然后去做负载均衡策略的
public RestTemplate restTemplate() {
    // HttpComponentsClientHttpRequestFactory httpRequestFactory = new
    // HttpComponentsClientHttpRequestFactory();
    // httpRequestFactory.setConnectionRequestTimeout(1000);
    // httpRequestFactory.setConnectTimeout(1000);
    // httpRequestFactory.setReadTimeout(3000);
    return new RestTemplate(httpRequestFactory());
}
项目:REST-Web-Services    文件:SettingsController.java   
/**
 * 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");
}
项目:spring-credhub    文件:CredHubClient.java   
/**
 * Create a {@link RestTemplate} configured for communication with a CredHub server.
 *
 * @param baseUri the base URI for the CredHub server
 * @param clientHttpRequestFactory the {@link ClientHttpRequestFactory} to use when
 * creating new connections
 * @return a configured {@link RestTemplate}
 */
public static RestTemplate createRestTemplate(String baseUri,
        ClientHttpRequestFactory clientHttpRequestFactory) {
    RestTemplate restTemplate = new RestTemplate();

    configureRestTemplate(restTemplate, baseUri, clientHttpRequestFactory);

    return restTemplate;
}
项目:keti    文件:PolicyEvaluationWithAttributeConnectorIT.java   
private void setRestTemplateInterceptor(final RestTemplate restTemplate) {
    restTemplate.setInterceptors(Collections.singletonList(
            new TraceRestTemplateInterceptor(this.tracer, new ZipkinHttpSpanInjector(),
                    new HttpTraceKeysInjector(this.tracer, new TraceKeys()))));
}
项目:Sound.je    文件:FacebookReader.java   
/**
 * This is the method that actually makes the http request
 *
 * @param url              request url
 * @param deconstructClass class of request object
 * @param <T>              type of request object this is
 * @return request object
 */
private <T> T request(final String url, final Class<T> deconstructClass) {
    final RestTemplate restTemplate = new RestTemplate();
    T deconstructedResponse = null;

    try {
        deconstructedResponse = restTemplate.getForObject(url, deconstructClass);
    } catch (HttpClientErrorException err) {
        logger.info("[FacebookReader] [request] Failure To Retrieve Facebook Resource (" + url + ")", err);
    }

    return deconstructedResponse;
}