org.springframework.web.client.RestTemplate类的使用及代码示例

x33g5p2x  于2022-01-28 转载在 其他  
字(13.1k)|赞(0)|评价(0)|浏览(428)

本文整理了Java中org.springframework.web.client.RestTemplate类的一些代码示例,展示了RestTemplate类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。RestTemplate类的具体详情如下:
包路径:org.springframework.web.client.RestTemplate
类名称:RestTemplate

RestTemplate介绍

[英]Synchronous client to perform HTTP requests, exposing a simple, template method API over underlying HTTP client libraries such as the JDK HttpURLConnection, Apache HttpComponents, and others.

The RestTemplate offers templates for common scenarios by HTTP method, in addition to the generalized exchange and execute methods that support of less frequent cases.

NOTE: As of 5.0, the non-blocking, reactive org.springframework.web.reactive.client.WebClient offers a modern alternative to the RestTemplate with efficient support for both sync and async, as well as streaming scenarios. The RestTemplatewill be deprecated in a future version and will not have major new features added going forward. See the WebClient section of the Spring Framework reference documentation for more details and example code.
[中]同步客户端执行HTTP请求,在底层HTTP客户端库(如JDK HttpURLConnection、Apache HttpComponents等)上公开一个简单的模板方法API。
RestTemplate通过HTTP方法为常见场景提供模板,此外还提供了支持不太常见情况的通用交换和执行方法。
注:从5.0开始,非阻塞、反应性组织。springframework。网状物反应性。客户WebClient为RestTemplate提供了一种现代的替代方案,对同步和异步以及流媒体场景都提供了高效的支持。RestTemplate在未来的版本中将被弃用,未来不会添加主要的新功能。有关更多详细信息和示例代码,请参阅Spring框架参考文档的WebClient部分。

代码示例

代码示例来源:origin: forezp/SpringCloudLearning

@Bean
@LoadBalanced
RestTemplate restTemplate() {
  return new RestTemplate();
}

代码示例来源:origin: ctripcorp/apollo

private <T> T doExecute(HttpMethod method, ServiceDTO service, String path, Object request,
            Class<T> responseType,
            Object... uriVariables) {
 T result = null;
 switch (method) {
  case GET:
   result = restTemplate.getForObject(parseHost(service) + path, responseType, uriVariables);
   break;
  case POST:
   result =
     restTemplate.postForEntity(parseHost(service) + path, request, responseType, uriVariables).getBody();
   break;
  case PUT:
   restTemplate.put(parseHost(service) + path, request, uriVariables);
   break;
  case DELETE:
   restTemplate.delete(parseHost(service) + path, uriVariables);
   break;
  default:
   throw new UnsupportedOperationException(String.format("unsupported http method(method=%s)", method));
 }
 return result;
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void exchangeGet() throws Exception {
  HttpHeaders requestHeaders = new HttpHeaders();
  requestHeaders.set("MyHeader", "MyValue");
  HttpEntity<String> requestEntity = new HttpEntity<>(requestHeaders);
  ResponseEntity<String> response =
      template.exchange(baseUrl + "/{method}", HttpMethod.GET, requestEntity, String.class, "get");
  assertEquals("Invalid content", helloWorld, response.getBody());
}

代码示例来源:origin: stackoverflow.com

RestTemplate restTemplate = new RestTemplate();

String url = "endpoint url";
String requestJson = "{\"queriedQuestion\":\"Is there pain in your hand?\"}";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);

HttpEntity<String> entity = new HttpEntity<String>(requestJson,headers);
String answer = restTemplate.postForObject(url, entity, String.class);
System.out.println(answer);

代码示例来源:origin: liuyangming/ByteTCC

@org.springframework.context.annotation.Primary
@org.springframework.cloud.client.loadbalancer.LoadBalanced
@org.springframework.context.annotation.Bean
public RestTemplate defaultRestTemplate(@Autowired CompensableRequestInterceptor compensableRequestInterceptor) {
  RestTemplate restTemplate = new RestTemplate();
  restTemplate.getInterceptors().add(compensableRequestInterceptor);
  return restTemplate;
}

代码示例来源:origin: stackoverflow.com

MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
headers.add("Authorization", "Basic " + base64Creds);
headers.add("Content-Type", "application/json");

RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

HttpEntity<ObjectToPass> request = new HttpEntity<ObjectToPass>(ObjectToPass, headers);

restTemplate.postForObject(urlPost, request, Boolean.class);

代码示例来源:origin: macrozheng/mall

@Bean
  public RestTemplate restTemplate(){
    return new RestTemplate();
  }
}

代码示例来源:origin: prontera/spring-cloud-rest-tcc

@LoadBalanced
@Bean
public RestTemplate restTemplate() {
  final RestTemplate template = new RestTemplate();
  template.setErrorHandler(new TccResponseErrorHandler());
  return template;
}

代码示例来源:origin: liuyangming/ByteTCC

@org.springframework.context.annotation.Bean("compensableRestTemplate")
@org.springframework.cloud.client.loadbalancer.LoadBalanced
public RestTemplate transactionTemplate(@Autowired ClientHttpRequestFactory requestFactory) {
  RestTemplate restTemplate = new RestTemplate();
  restTemplate.setRequestFactory(requestFactory);
  SpringCloudBeanRegistry registry = SpringCloudBeanRegistry.getInstance();
  registry.setRestTemplate(restTemplate);
  return restTemplate;
}

代码示例来源:origin: cloudfoundry/uaa

public static String createInvitation(String baseUrl, String uaaUrl, String username, String userEmail, String origin, String redirectUri, String loginToken, String scimToken) {
  HttpHeaders headers = new HttpHeaders();
  headers.add("Authorization", "Bearer " + scimToken);
  RestTemplate uaaTemplate = new RestTemplate();
  ScimUser scimUser = new ScimUser();
  scimUser.setPassword("password");
    ResponseEntity<ScimUser> response = uaaTemplate.exchange(uaaUrl + "/Users", POST, request, ScimUser.class);
    if (response.getStatusCode().value()!= HttpStatus.CREATED.value()) {
      throw new IllegalStateException("Unable to create test user:"+scimUser);
    userId = response.getBody().getId();
  } else {
    scimUser.setVerified(false);
  HttpHeaders invitationHeaders = new HttpHeaders();
  invitationHeaders.add("Authorization", "Bearer " + loginToken);
  ExpiringCode expiringCode = new ExpiringCode(null, expiry, "{\"origin\":\"" + origin + "\", \"client_id\":\"app\", \"redirect_uri\":\"" + redirectUri + "\", \"user_id\":\"" + userId + "\", \"email\":\"" + userEmail + "\"}", null);
  HttpEntity<ExpiringCode> expiringCodeRequest = new HttpEntity<>(expiringCode, invitationHeaders);
  ResponseEntity<ExpiringCode> expiringCodeResponse = uaaTemplate.exchange(uaaUrl + "/Codes", POST, expiringCodeRequest, ExpiringCode.class);
  expiringCode = expiringCodeResponse.getBody();
  return expiringCode.getCode();

代码示例来源:origin: spring-projects/spring-framework

@Test
public void testRequestToFooHandler() throws Exception {
  URI url = new URI("http://localhost:" + this.port + "/foo");
  RequestEntity<Void> request = RequestEntity.get(url).build();
  ResponseEntity<byte[]> response = new RestTemplate().exchange(request, byte[].class);
  assertEquals(HttpStatus.OK, response.getStatusCode());
  assertArrayEquals("foo".getBytes("UTF-8"), response.getBody());
}

代码示例来源:origin: mitreid-connect/OpenID-Connect-Java-Spring-Server

@Override
public RegisteredClient load(ServerConfiguration serverConfig) throws Exception {
  RestTemplate restTemplate = new RestTemplate(httpFactory);
    String serializedClient = gson.toJson(jsonRequest);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.setAccept(Lists.newArrayList(MediaType.APPLICATION_JSON));
      String registered = restTemplate.postForObject(serverConfig.getRegistrationEndpointUri(), entity, String.class);
        String registered = restTemplate.exchange(knownClient.getRegistrationClientUri(), HttpMethod.GET, entity, String.class).getBody();

代码示例来源:origin: spring-projects/spring-integration-samples

@Test
public void testGetEmployeeAsJson() throws Exception{
  Map<String, Object> employeeSearchMap = getEmployeeSearchMap("0");
  final String fullUrl = "http://localhost:8080/rest-http/services/employee/{id}/search?format=json";
  HttpHeaders headers = getHttpHeadersWithUserCredentials(new HttpHeaders());
  headers.add("Accept", "application/json");
  HttpEntity<Object> request = new HttpEntity<Object>(headers);
  ResponseEntity<?> httpResponse = restTemplate.exchange(fullUrl, HttpMethod.GET, request, EmployeeList.class, employeeSearchMap);
  logger.info("Return Status :"+httpResponse.getHeaders().get("X-Return-Status"));
  logger.info("Return Status Message :"+httpResponse.getHeaders().get("X-Return-Status-Msg"));
  assertTrue(httpResponse.getStatusCode().equals(HttpStatus.OK));
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  jaxbJacksonObjectMapper.writeValue(out, httpResponse.getBody());
  logger.info(new String(out.toByteArray()));
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void testRequestToHeaderSettingHandler() throws Exception {
  URI url = new URI("http://localhost:" + this.port + "/header");
  RequestEntity<Void> request = RequestEntity.get(url).build();
  ResponseEntity<byte[]> response = new RestTemplate().exchange(request, byte[].class);
  assertEquals(HttpStatus.OK, response.getStatusCode());
  assertEquals("bar", response.getHeaders().getFirst("foo"));
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void exchange() throws Exception {
  mockTextPlainHttpMessageConverter();
  HttpHeaders requestHeaders = new HttpHeaders();
  mockSentRequest(POST, "http://example.com", requestHeaders);
  mockResponseStatus(HttpStatus.OK);
  String expected = "42";
  mockResponseBody(expected, MediaType.TEXT_PLAIN);
  HttpHeaders entityHeaders = new HttpHeaders();
  entityHeaders.set("MyHeader", "MyValue");
  HttpEntity<String> entity = new HttpEntity<>("Hello World", entityHeaders);
  ResponseEntity<String> result = template.exchange("http://example.com", POST, entity, String.class);
  assertEquals("Invalid POST result", expected, result.getBody());
  assertEquals("Invalid Content-Type", MediaType.TEXT_PLAIN, result.getHeaders().getContentType());
  assertEquals("Invalid Accept header", MediaType.TEXT_PLAIN_VALUE, requestHeaders.getFirst("Accept"));
  assertEquals("Invalid custom header", "MyValue", requestHeaders.getFirst("MyHeader"));
  assertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode());
  verify(response).close();
}

代码示例来源:origin: spring-projects/spring-integration-samples

public static void main(String[] args) throws Exception{
    RestTemplate template = new RestTemplate();
    Resource s2logo = new ClassPathResource(resourcePath);
    MultiValueMap<String, Object> multipartMap = new LinkedMultiValueMap<String, Object>();
    multipartMap.add("company", "SpringSource");
    multipartMap.add("company-logo", s2logo);
    logger.info("Created multipart request: " + multipartMap);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(new MediaType("multipart", "form-data"));
    HttpEntity<Object> request = new HttpEntity<Object>(multipartMap, headers);
    logger.info("Posting request to: " + uri);
    ResponseEntity<?> httpResponse = template.exchange(uri, HttpMethod.POST, request, Object.class);
    if (!httpResponse.getStatusCode().equals(HttpStatus.OK)){
      logger.error("Problems with the request. Http status: " + httpResponse.getStatusCode());
    }
  }
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void writeOnly() throws Exception {
  RestTemplate restTemplate = new RestTemplate();
  this.body = randomBytes();
  RequestEntity<byte[]> request = RequestEntity.post(
      new URI("http://localhost:" + port)).body(
          "".getBytes(StandardCharsets.UTF_8));
  ResponseEntity<byte[]> response = restTemplate.exchange(request, byte[].class);
  assertArrayEquals(body, response.getBody());
}

代码示例来源:origin: spring-cloud/spring-cloud-config

HttpHeaders headers = new HttpHeaders();
if (StringUtils.hasText(token)) {
  headers.add(CONSUL_TOKEN, token);
ResponseEntity<List<String>> response = this.restTemplate.exchange(WATCH_URL,
    HttpMethod.GET, request, RESPONSE_TYPE, params.toArray());
if (response.getStatusCode().is2xxSuccessful()) {
  String consulIndex = response.getHeaders().getFirst(CONSUL_INDEX);
  return consulIndex;
if (!e.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
  LOG.error("Unable to watch consul path " + this.path, e);
  return null;

代码示例来源:origin: spring-projects/spring-framework

@Test
public void bar() {
  ResponseEntity<String> result =
      restTemplate.getForEntity("http://localhost:" + port + "/foo/bar", String.class);
  assertEquals(HttpStatus.OK, result.getStatusCode());
  assertEquals("/foo/bar", result.getBody());
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void getForEntity() throws Exception {
  HttpHeaders requestHeaders = new HttpHeaders();
  mockSentRequest(GET, "http://example.com", requestHeaders);
  mockTextPlainHttpMessageConverter();
  mockResponseStatus(HttpStatus.OK);
  String expected = "Hello World";
  mockTextResponseBody(expected);
  ResponseEntity<String> result = template.getForEntity("http://example.com", String.class);
  assertEquals("Invalid GET result", expected, result.getBody());
  assertEquals("Invalid Accept header", MediaType.TEXT_PLAIN_VALUE, requestHeaders.getFirst("Accept"));
  assertEquals("Invalid Content-Type header", MediaType.TEXT_PLAIN, result.getHeaders().getContentType());
  assertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode());
  verify(response).close();
}

相关文章