org.springframework.web.client.RestTemplate.postForEntity()方法的使用及代码示例

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

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

RestTemplate.postForEntity介绍

暂无

代码示例

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

@ApiOperation("postForEntity jsonBody")
@RequestMapping(value = "/post", method = RequestMethod.POST)
@ResponseBody
public Object postForEntity(@RequestBody PmsBrand brand) {
  String url = HOST_MALL_ADMIN + "/brand/create";
  ResponseEntity<CommonResult> responseEntity = restTemplate.postForEntity(url, brand, CommonResult.class);
  return responseEntity.getBody();
}

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

private void invokerAccountService(int orderMoney) {
    String url = "http://127.0.0.1:18084/account";
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();

    map.add("userId", USER_ID);
    map.add("money", orderMoney + "");

    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(
        map, headers);

    ResponseEntity<String> response = restTemplate.postForEntity(url, request,
        String.class);
  }
}

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

@ApiOperation("postForEntity form")
  @RequestMapping(value = "/post3", method = RequestMethod.POST)
  @ResponseBody
  public Object postForEntity3(@RequestParam String name) {
    String url = HOST_MALL_ADMIN + "/productAttribute/category/create";
    //设置头信息
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    //构造表单参数
    MultiValueMap<String, String> params= new LinkedMultiValueMap<>();
    params.add("name", name);
    HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
    ResponseEntity<CommonResult> responseEntity = restTemplate.postForEntity(url, requestEntity, CommonResult.class);
    return responseEntity.getBody();
  }
}

代码示例来源:origin: codecentric/spring-boot-admin

@Override
protected Mono<Void> doNotify(InstanceEvent event, Instance instance) {
  return Mono.fromRunnable(
    () -> restTemplate.postForEntity(url, createPagerdutyEvent(event, instance), Void.class));
}

代码示例来源:origin: codecentric/spring-boot-admin

@Override
protected Mono<Void> doNotify(InstanceEvent event, Instance instance) {
  if (webhookUrl == null) {
    return Mono.error(new IllegalStateException("'webhookUrl' must not be null."));
  }
  return Mono.fromRunnable(
    () -> restTemplate.postForEntity(webhookUrl, createMessage(event, instance), Void.class));
}

代码示例来源:origin: codecentric/spring-boot-admin

@Override
protected Mono<Void> doNotify(InstanceEvent event, Instance instance) {
  if (webhookUrl == null) {
    return Mono.error(new IllegalStateException("'webhookUrl' must not be null."));
  }
  return Mono.fromRunnable(() -> restTemplate.postForEntity(
    webhookUrl,
    createDiscordNotification(event, instance),
    Void.class
  ));
}

代码示例来源:origin: codecentric/spring-boot-admin

@Override
protected Mono<Void> doNotify(InstanceEvent event, Instance instance) {
  return Mono.fromRunnable(() -> restTemplate.postForEntity(buildUrl(),
    createHipChatNotification(event, instance),
    Void.class
  ));
}

代码示例来源: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 removeFailedPathVariablesAnd() {
  ResponseEntity<String> result =
      restTemplate.postForEntity("http://localhost:" + port + "/qux/quux", "", String.class);
  assertEquals(HttpStatus.OK, result.getStatusCode());
  assertEquals("{}", result.getBody());
}

代码示例来源:origin: rampatra/jbot

protected final ResponseEntity<String> reply(Event event) {
  sendTypingOffIndicator(event.getRecipient());
  logger.debug("Send message: {}", event.toString());
  try {
    return restTemplate.postForEntity(fbSendUrl, event, String.class);
  } catch (HttpClientErrorException e) {
    logger.error("Send message error: Response body: {} \nException: ", e.getResponseBodyAsString(), e);
    return new ResponseEntity<>(e.getResponseBodyAsString(), e.getStatusCode());
  }
}

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

private ResponseEntity<String> makePasswordGrantRequest(String userName, String password, String clientId, String clientSecret, String url) {
  HttpHeaders headers = new HttpHeaders();
  headers.setAccept(Arrays.asList(APPLICATION_JSON));
  headers.add("Authorization", testAccounts.getAuthorizationHeader(clientId, clientSecret));
  MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
  params.add("grant_type", "password");
  params.add("username", userName);
  params.add("password", password);
  HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);
  RestTemplate template = getRestTemplate();
  return template.postForEntity(url, request, String.class);
}

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

public static void addMemberToGroup(RestTemplate client,
                  String url,
                  String userId,
                  String groupId
) {
  ScimGroupMember groupMember = new ScimGroupMember(userId);
  ResponseEntity<String> response = client.postForEntity(url + "/Groups/{groupId}/members", groupMember, String.class, groupId);
  assertEquals(HttpStatus.CREATED, response.getStatusCode());
}

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

private ScimGroup createGroup(String name, ScimGroupMember... members) {
  ScimGroup g = new ScimGroup(null, name, IdentityZoneHolder.get().getId());
  List<ScimGroupMember> m = members != null ? Arrays.asList(members) : Collections.<ScimGroupMember>emptyList();
  g.setMembers(m);
  ScimGroup g1 = client.postForEntity(serverRunning.getUrl(groupEndpoint), g, ScimGroup.class).getBody();
  assertEquals(name, g1.getDisplayName());
  assertEquals(m.size(), g1.getMembers().size());
  groupIds.add(g1.getId());
  return g1;
}

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

@Test
public void postForEntity() throws Exception {
  mockTextPlainHttpMessageConverter();
  HttpHeaders requestHeaders = new HttpHeaders();
  mockSentRequest(POST, "http://example.com", requestHeaders);
  mockResponseStatus(HttpStatus.OK);
  String expected = "42";
  mockResponseBody(expected, MediaType.TEXT_PLAIN);
  ResponseEntity<String> result = template.postForEntity("http://example.com", "Hello World", 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 status code", HttpStatus.OK, result.getStatusCode());
  verify(response).close();
}

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

@Test  // SPR-16132
public void followUpRequestAfterFailure() {
  MockRestServiceServer server = MockRestServiceServer.bindTo(this.restTemplate).build();
  server.expect(requestTo("/some-service/some-endpoint"))
      .andRespond(request -> { throw new SocketException("pseudo network error"); });
  server.expect(requestTo("/reporting-service/report-error"))
      .andExpect(method(POST)).andRespond(withSuccess());
  try {
    this.restTemplate.getForEntity("/some-service/some-endpoint", String.class);
  }
  catch (Exception ex) {
    this.restTemplate.postForEntity("/reporting-service/report-error", ex.toString(), String.class);
  }
  server.verify();
}

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

private ScimUser createUser(String username, String password) {
  ScimUser user = new ScimUser();
  user.setUserName(username);
  user.setName(new ScimUser.Name(username, username));
  user.addEmail(username);
  user.setVerified(true);
  user.setPassword(password);
  ResponseEntity<ScimUser> result = client.postForEntity(serverRunning.getUrl(userEndpoint), user, ScimUser.class);
  assertEquals(HttpStatus.CREATED, result.getStatusCode());
  return result.getBody();
}

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

@Test
public void postForEntityNull() throws Exception {
  mockTextPlainHttpMessageConverter();
  HttpHeaders requestHeaders = new HttpHeaders();
  mockSentRequest(POST, "http://example.com", requestHeaders);
  mockResponseStatus(HttpStatus.OK);
  HttpHeaders responseHeaders = new HttpHeaders();
  responseHeaders.setContentType(MediaType.TEXT_PLAIN);
  responseHeaders.setContentLength(10);
  given(response.getHeaders()).willReturn(responseHeaders);
  given(response.getBody()).willReturn(StreamUtils.emptyInput());
  given(converter.read(String.class, response)).willReturn(null);
  ResponseEntity<String> result = template.postForEntity("http://example.com", null, String.class);
  assertFalse("Invalid POST result", result.hasBody());
  assertEquals("Invalid Content-Type", MediaType.TEXT_PLAIN, result.getHeaders().getContentType());
  assertEquals("Invalid content length", 0, requestHeaders.getContentLength());
  assertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode());
  verify(response).close();
}

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

private ResponseEntity<ScimUser> createUser(String username, String firstName, String lastName, String email) {
  ScimUser user = new ScimUser();
  user.setUserName(username);
  user.setPassword("password");
  user.setName(new ScimUser.Name(firstName, lastName));
  user.addEmail(email);
  return client.postForEntity(serverRunning.getUrl(userEndpoint), user, ScimUser.class);
}

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

private ResponseEntity<ScimUser> createUser(String username, String firstName, String lastName,
        String email, boolean verified) {
  ScimUser user = new ScimUser();
  user.setPassword("password");
  user.setUserName(username);
  user.setName(new ScimUser.Name(firstName, lastName));
  user.addEmail(email);
  user.setVerified(verified);
  return client.postForEntity(serverRunning.getUrl(userEndpoint), user, ScimUser.class);
}

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

private ResponseEntity<ScimUser> createUser(String username, String firstName, String lastName,
        String email, boolean verified) {
  ScimUser user = new ScimUser();
  user.setUserName(username);
  user.setName(new ScimUser.Name(firstName, lastName));
  user.addEmail(email);
  user.setVerified(verified);
  user.setActive(true);
  user.setPassword("s3Cret");
  return client.postForEntity(serverRunning.getUrl(userEndpoint), user, ScimUser.class);
}

相关文章