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


Java RestTemplate.getForObject方法代码示例

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


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

示例1: 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>();
}
 
开发者ID:twitch4j,项目名称:twitch4j,代码行数:32,代码来源:StreamEndpoint.java

示例2: getRecommendations

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
/**
 * Get recommended streams for User (Unofficial)
 * Gets a list of recommended streams for a user.
 * Requires Scope: none
 *
 * @param credential OAuthCredential of the user, you want to request recommendations for.
 * @return StreamList of random Streams.
 */
@Unofficial
public List<Recommendation> getRecommendations(OAuthCredential credential) {
	// Endpoint
	String requestUrl = String.format("%s/streams/recommended", Endpoints.API.getURL());
	RestTemplate restTemplate = getTwitchClient().getRestClient().getRestTemplate();

	// Parameters
	restTemplate.getInterceptors().add(new QueryRequestInterceptor("oauth_token", credential.getToken()));

	// REST Request
	try {
		Logger.trace(this, "Rest Request to [%s]", requestUrl);
		RecommendationList responseObject = restTemplate.getForObject(requestUrl, RecommendationList.class);

		return responseObject.getRecommendedStreams();
	} 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 null;
}
 
开发者ID:twitch4j,项目名称:twitch4j,代码行数:33,代码来源:StreamEndpoint.java

示例3: getGames

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
/**
 * Endpoint: Search Games
 * Searches for games based on a specified query parameter. A game is returned if the query parameter is matched entirely or partially, in the game name.
 * Requires Scope: none
 *
 * @param query search query
 * @param live Whether only games that are live should be returned. This argument is optional.
 * @return A list of games matching the query.
 */
public List<Game> getGames(String query, Optional<Boolean> live) {
	// Endpoint
	String requestUrl = String.format("%s/search/games", Endpoints.API.getURL());
	RestTemplate restTemplate = getTwitchClient().getRestClient().getRestTemplate();

	// Parameters
	restTemplate.getInterceptors().add(new QueryRequestInterceptor("query", query));
	restTemplate.getInterceptors().add(new QueryRequestInterceptor("live", live.orElse(false).toString()));

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

		return responseObject.getGames();
	} 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 null;
}
 
开发者ID:twitch4j,项目名称:twitch4j,代码行数:33,代码来源:SearchEndpoint.java

示例4: byId

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
@Override
public ProductInformation byId(String id) {
    Map<String, String> uriParameters = new HashMap<>();
    uriParameters.put("id", id);
    RestTemplate rest = new RestTemplate();
    InventoryItemAmount amount =
            rest.getForObject(piSUBuilder.url("inventory"),
                    InventoryItemAmount.class,
                    uriParameters);
    log.info("amount {}.",amount);
    if ( amount.getAmount() > 0) {
        log.info("There items from {}. We are offering",id);
        return rest.getForObject(piSUBuilder.url("pi"),
                ProductInformation.class,
                uriParameters);
    } else {
        log.info("There are no items from {}. Amount is {}",id,amount);
        return ProductInformation.emptyProductInformation;
    }
}
 
开发者ID:PacktPublishing,项目名称:Java-9-Programming-By-Example,代码行数:21,代码来源:RestClientProductLookup.java

示例5: getSummary

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
/**
 * Get Streams Summary
 * <p>
 * Gets a summary of all live streams.
 * Requires Scope: none
 *
 * @param game Restricts the summary stats to the specified game.
 * @return A <code>StreamSummary</code> object, that contains the total number of live streams and viewers.
 */
public StreamSummary getSummary(Optional<Game> game) {
	// Endpoint
	String requestUrl = String.format("%s/streams/summary", Endpoints.API.getURL());
	RestTemplate restTemplate = getTwitchClient().getRestClient().getRestTemplate();

	// Parameters
	restTemplate.getInterceptors().add(new QueryRequestInterceptor("game", game.map(Game::getName).orElse("")));

	// REST Request
	try {
		Logger.trace(this, "Rest Request to [%s]", requestUrl);
		StreamSummary responseObject = restTemplate.getForObject(requestUrl, StreamSummary.class);

		return responseObject;
	} 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 null;
}
 
开发者ID:twitch4j,项目名称:twitch4j,代码行数:33,代码来源:StreamEndpoint.java

示例6: getFeedPosts

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
/**
 * Gets posts from a specified channel feed.
 *
 * @param channelId    The channel id, which the posts should be retrieved from.
 * @param limit        Maximum number of most-recent objects to return. Default: 10. Maximum: 100.
 * @param cursor       Tells the server where to start fetching the next set of results in a multi-page response.
 * @param commentLimit Specifies the number of most-recent comments on posts that are included in the response. Default: 5. Maximum: 5.
 * @return posts from a specified channel feed.
 */
public List<ChannelFeedPost> getFeedPosts(Long channelId, Optional<Long> limit, Optional<String> cursor, Optional<Long> commentLimit) {
	// Endpoint
	String requestUrl = String.format("%s/feed/%s/posts", Endpoints.API.getURL(), channelId);
	RestTemplate restTemplate = getTwitchClient().getRestClient().getRestTemplate();

	// Parameters
	restTemplate.getInterceptors().add(new QueryRequestInterceptor("limit", limit.orElse(10l).toString()));
	restTemplate.getInterceptors().add(new QueryRequestInterceptor("cursor", cursor.orElse("")));
	restTemplate.getInterceptors().add(new QueryRequestInterceptor("comments", commentLimit.orElse(5l).toString()));

	// REST Request
	try {
		Logger.trace(this, "Rest Request to [%s]", requestUrl);
		ChannelFeed responseObject = restTemplate.getForObject(requestUrl, ChannelFeed.class);

		return responseObject.getPosts();
	} 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 new ArrayList<ChannelFeedPost>();
}
 
开发者ID:twitch4j,项目名称:twitch4j,代码行数:35,代码来源:ChannelFeedEndpoint.java

示例7: DataFlowTemplate

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
/**
 * Setup a {@link DataFlowTemplate} using the provide {@link RestTemplate}. Any missing Mixins for Jackson will be
 * added implicitly. For more information, please see {@link #prepareRestTemplate(RestTemplate)}.
 *
 * @param baseURI Must not be null
 * @param restTemplate Must not be null
 */
public DataFlowTemplate(URI baseURI, RestTemplate restTemplate) {

	Assert.notNull(baseURI, "The provided baseURI must not be null.");
	Assert.notNull(restTemplate, "The provided restTemplate must not be null.");

	this.restTemplate = prepareRestTemplate(restTemplate);
	final ResourceSupport resourceSupport = restTemplate.getForObject(baseURI, ResourceSupport.class);
	this.runtimeOperations = new RuntimeTemplate(restTemplate, resourceSupport);
	this.appRegistryOperations = new AppRegistryTemplate(restTemplate, resourceSupport);
	this.completionOperations = new CompletionTemplate(restTemplate,
		resourceSupport.getLink("completions/stream"),
		resourceSupport.getLink("completions/task"));
	if (resourceSupport.hasLink(ApplicationTemplate.DEFINITIONS_REL)) {
		this.applicationOperations = new ApplicationTemplate(restTemplate, resourceSupport);
	}
	else {
		this.applicationOperations = null;
	}
}
 
开发者ID:spring-cloud,项目名称:spring-cloud-dashboard,代码行数:27,代码来源:DataFlowTemplate.java

示例8: 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));
}
 
开发者ID:HotelsDotCom,项目名称:waggle-dance,代码行数:21,代码来源:WaggleDanceIntegrationTest.java

示例9: getTopCommunities

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
/**
 * Endpoint: Get Top Communities
 * Gets a specified community.
 * Requires Scope: none
 *
 * @param limit  Maximum number of most-recent objects to return. Default: 25. Maximum: 100.
 * @param cursor Tells the server where to start fetching the next set of results in a multi-page response.
 * @return The top communities.
 */
public CommunityList getTopCommunities(Optional<Long> limit, Optional<String> cursor) {
	// Endpoint
	String requestUrl = String.format("%s/communities/top", Endpoints.API.getURL());
	RestTemplate restTemplate = getTwitchClient().getRestClient().getRestTemplate();

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

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

		return responseObject;
	} 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 null;
}
 
开发者ID:twitch4j,项目名称:twitch4j,代码行数:33,代码来源:CommunityEndpoint.java

示例10: request

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
/**
 * 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("[YoutubeReader] [request] Failure To Retrieve YouTube Resource (" + url + ")", err);
    }

    return deconstructedResponse;
}
 
开发者ID:mhaddon,项目名称:Sound.je,代码行数:21,代码来源:YoutubeReader.java

示例11: isServerListening

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
public static boolean isServerListening(final URI url) {
    RestTemplate restTemplate = new RestTemplate();
    try {
        restTemplate.getForObject(url, String.class);
    } catch (RestClientException e) {
        if (e.getCause() instanceof ConnectException) {
            return false;
        }
    }
    return true;
}
 
开发者ID:eclipse,项目名称:keti,代码行数:12,代码来源:ACSTestUtil.java

示例12: executeFindSpaceRequest

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
private CloudSpace executeFindSpaceRequest(RestTemplate restTemplate, String url, Map<String, Object> urlVariables) {
    String response = restTemplate.getForObject(url, String.class, urlVariables);
    Map<String, Object> parsedResponse = parseResponse(response);
    validateResponse(parsedResponse);
    return toCloudSpace(parsedResponse);
}
 
开发者ID:SAP,项目名称:cf-mta-deploy-service,代码行数:7,代码来源:CFOptimizedSpaceGetter.java

示例13: LMClassifier

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
/**
 * Creates a new REST service client and connects to the language model
 *
 * @param server server
 * @param port   port
 */
public LMClassifier(String server, int port)
{
    uri = "http://" + server + ":" + port + "/logprob/{sentence}";

    Map<String, String> params = new HashMap<>();
    params.put("sentence", "This is a test");

    restTemplate = new RestTemplate();
    restTemplate.getForObject(uri, Double.class, params);
}
 
开发者ID:UKPLab,项目名称:argument-reasoning-comprehension-task,代码行数:17,代码来源:LMClassifier.java

示例14: run

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
public void run(String[] args) {
		RestTemplate restTemplate = new RestTemplate(); 
		Team team = restTemplate.getForObject("http://localhost:8080/team", Team.class);
		
		/* ripete tante volte, altrimenti si perde tra i log di Spring Boot */
		for (int i=0; i<10; i++) {
			logger.info( team.getName() );
//			System.out.println( team.getName() );
		}
	}
 
开发者ID:aswroma3,项目名称:asw,代码行数:11,代码来源:TeamRestClient.java

示例15: main

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
public static void main(String[] args)
		throws IOException, URISyntaxException {
	RestTemplate restTemplate = new RestTemplate();
	GeonamesSearchResult searchResult = restTemplate.getForObject(
			"http://api.geonames.org/searchJSON?q={q}&username={username}",
		GeonamesSearchResult.class,
			ImmutableMap.of("q", "kabupaten garut", "username", "ceefour"));
	LOG.info("Body (GeonamesSearchResult): {}", searchResult);
	for (Geoname child : searchResult.getGeonames()) {
		LOG.info("Place: {} ({}, {})",
				child.getToponymName(), child.getLat(), child.getLng());
	}
}
 
开发者ID:ceefour,项目名称:java-web-services-training,代码行数:14,代码来源:GetGeonamesApplication.java


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