本文整理汇总了Java中org.springframework.web.client.RestTemplate类的典型用法代码示例。如果您正苦于以下问题:Java RestTemplate类的具体用法?Java RestTemplate怎么用?Java RestTemplate使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
RestTemplate类属于org.springframework.web.client包,在下文中一共展示了RestTemplate类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getChatters
import org.springframework.web.client.RestTemplate; //导入依赖的package包/类
/**
* 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();
}
示例2: restTemplate
import org.springframework.web.client.RestTemplate; //导入依赖的package包/类
@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);
}
示例3: 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");
}
示例4: testExchange
import org.springframework.web.client.RestTemplate; //导入依赖的package包/类
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());
}
示例5: getFeatured
import org.springframework.web.client.RestTemplate; //导入依赖的package包/类
/**
* 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>();
}
示例6: restApiGetStatus
import org.springframework.web.client.RestTemplate; //导入依赖的package包/类
@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));
}
示例7: TracingRestTemplateTest
import org.springframework.web.client.RestTemplate; //导入依赖的package包/类
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();
}
示例8: SimpleB2CAuthenticationService
import org.springframework.web.client.RestTemplate; //导入依赖的package包/类
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;
}
示例9: getFollowed
import org.springframework.web.client.RestTemplate; //导入依赖的package包/类
/**
* 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>();
}
示例10: executeWS
import org.springframework.web.client.RestTemplate; //导入依赖的package包/类
/** 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;
}
}
示例11: getToken
import org.springframework.web.client.RestTemplate; //导入依赖的package包/类
/**
* 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();
}
示例12: sendViaMailgunApi
import org.springframework.web.client.RestTemplate; //导入依赖的package包/类
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.");
}
示例13: getRestTemplate
import org.springframework.web.client.RestTemplate; //导入依赖的package包/类
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;
}
示例14: getMore
import org.springframework.web.client.RestTemplate; //导入依赖的package包/类
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;
}
示例15: testStatusReleaseNameFound
import org.springframework.web.client.RestTemplate; //导入依赖的package包/类
@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);
}