Java Code Examples for org.springframework.web.client.resttemplate#postForEntity()
The following examples show how to use
org.springframework.web.client.resttemplate#postForEntity() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: XxxTest.java From x7 with Apache License 2.0 | 6 votes |
public ViewEntity testRestTemplate(){ SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); requestFactory.setConnectTimeout(60000); requestFactory.setReadTimeout(60000); String url = "http://127.0.0.1:8868/xxx/test/rest"; HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add("TX_XID", "eg564ssasdd"); CatTest cat = new CatTest(); cat.setType("TEST_CAT"); HttpEntity<CatTest> requestEntity = new HttpEntity<CatTest>(cat,httpHeaders); RestTemplate restTemplate = new RestTemplate(requestFactory); ResponseEntity<String> result = restTemplate.postForEntity(url, requestEntity,String.class); return ViewEntity.ok(result); }
Example 2
Source File: RestTemplateTest.java From spring-tutorials with Apache License 2.0 | 6 votes |
@Test public void test_POST() throws URISyntaxException { RestTemplate restTemplate = new RestTemplate(); URI uri = new URI(baseUrl); String body = "The Body"; ResponseEntity<String> response=restTemplate.postForEntity(baseUrl, body, String.class); HttpEntity<String> request = new HttpEntity<>(body); ResponseEntity<String> responseExchange=restTemplate.exchange(baseUrl, HttpMethod.POST, request, String.class); ResponseEntity<String> responseURI=restTemplate.postForEntity(uri, body, String.class); ResponseEntity<String> responseExchangeURI=restTemplate.exchange(uri, HttpMethod.POST, request, String.class); isTrue(response.getStatusCode()==HttpStatus.OK); isTrue(responseURI.getStatusCode()==HttpStatus.OK); isTrue(responseExchange.getStatusCode()==HttpStatus.OK); isTrue(responseExchangeURI.getStatusCode()==HttpStatus.OK); }
Example 3
Source File: SpringWebBeanResolutionTest.java From ogham with Apache License 2.0 | 6 votes |
@Test public void emailUsingThymeleafTemplateInAsyncMethodCantResolveUrls() throws MessagingException, IOException { RestTemplate rt = new RestTemplate(); // @formatter:off UriComponentsBuilder builder = UriComponentsBuilder.fromPath("async/email") .scheme("http") .host("localhost") .port(port) .queryParam("template", "web-beans-and-urls-resolution"); // @formatter:on rt.postForEntity(builder.toUriString(), new HttpEntity<>(""), Void.class); await().atMost(5, SECONDS).until(() -> hasError()); OghamAssertions.assertThat(greenMail) .receivedMessages() .count(is(0)); ErrorDto error = getError(); assertThat(error.getType()).isEqualTo(MessageNotSentException.class.getSimpleName()); ErrorDto cause = getRootCause(error.getCause()); assertThat(cause.getType()).isEqualTo(TemplateProcessingException.class.getSimpleName()); assertThat(cause.getMessage()).contains("Link base \"/fake/resources/foo.js\" cannot be context relative (/...) unless the context used for executing the engine implements the org.thymeleaf.context.IWebContext"); }
Example 4
Source File: ApiController.java From microservices-platform with Apache License 2.0 | 6 votes |
/** * 获取token */ public Map getAccessToken(String code) throws UnsupportedEncodingException { RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); byte[] authorization = (clientId + ":" + clientSecret).getBytes("UTF-8"); BASE64Encoder encoder = new BASE64Encoder(); String base64Auth = encoder.encode(authorization); headers.add("Authorization", "Basic " + base64Auth); MultiValueMap<String, String> param = new LinkedMultiValueMap<>(); param.add("code", code); param.add("grant_type", "authorization_code"); param.add("redirect_uri", redirectUri); param.add("scope", "app"); HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(param, headers); ResponseEntity<Map> response = restTemplate.postForEntity(accessTokenUri, request , Map.class); Map result = response.getBody(); return result; }
Example 5
Source File: SpringWebBeanResolutionTest.java From ogham with Apache License 2.0 | 6 votes |
@Test public void emailUsingThymeleafTemplateShouldResolveBeansAndUrls() throws MessagingException, IOException { RestTemplate rt = new RestTemplate(); // @formatter:off UriComponentsBuilder builder = UriComponentsBuilder.fromPath("email") .scheme("http") .host("localhost") .port(port); // @formatter:on rt.postForEntity(builder.toUriString(), new HttpEntity<>(""), Void.class); OghamAssertions.assertThat(greenMail) .receivedMessages() .count(is(1)) .message(0) .body() .contentAsString(isIdenticalHtml(resourceAsString("/thymeleaf/expected/web-beans-and-urls-resolution.html"))); }
Example 6
Source File: SpringWebBeanResolutionTest.java From ogham with Apache License 2.0 | 6 votes |
@Test public void smsUsingThymeleafTemplateInAsyncMethodCantResolveUrls() throws MessagingException, IOException { RestTemplate rt = new RestTemplate(); // @formatter:off UriComponentsBuilder builder = UriComponentsBuilder.fromPath("async/sms") .scheme("http") .host("localhost") .port(port) .queryParam("template", "web-beans-and-urls-resolution"); // @formatter:on rt.postForEntity(builder.toUriString(), new HttpEntity<>(""), Void.class); await().atMost(5, SECONDS).until(() -> hasError()); OghamAssertions.assertThat(smppServer) .receivedMessages() .count(is(0)); ErrorDto error = getError(); assertThat(error.getType()).isEqualTo(MessageNotSentException.class.getSimpleName()); ErrorDto cause = getRootCause(error.getCause()); assertThat(cause.getType()).isEqualTo(TemplateProcessingException.class.getSimpleName()); assertThat(cause.getMessage()).contains("Link base \"/fake/resources/foo.js\" cannot be context relative (/) or page relative unless you implement the org.thymeleaf.context.IWebContext"); }
Example 7
Source File: SpringWebBeanResolutionTest.java From ogham with Apache License 2.0 | 6 votes |
@Test public void smsUsingThymeleafTemplateShouldResolveBeansAndUrls() throws MessagingException, IOException { RestTemplate rt = new RestTemplate(); // @formatter:off UriComponentsBuilder builder = UriComponentsBuilder.fromPath("sms") .scheme("http") .host("localhost") .port(port); // @formatter:on rt.postForEntity(builder.toUriString(), new HttpEntity<>(""), Void.class); OghamAssertions.assertThat(smppServer) .receivedMessages() .count(is(1)) .message(0) .content(is(resourceAsString("/thymeleaf/expected/web-beans-and-urls-resolution.txt"))); }
Example 8
Source File: ExecuteHandler.java From spring-cloud-shop with MIT License | 5 votes |
@Override public void execute(final String jobName, final String jobGroup) { // 1. 获取数据库执行的job任务 JobInfoMapper jobInfoMapper = ShopSpringContext.getBean(JobInfoMapper.class); JobInfo jobInfo = new JobInfo(); jobInfo.setJobName(jobName); jobInfo.setJobStatus(JobStatusEnums.NORMAL.getCode()); JobInfo selectJobInfo = jobInfoMapper.selectOne(new QueryWrapper<>(jobInfo)); // 访问的资源请求地址 if (Objects.nonNull(selectJobInfo)) { Map<String, String> paramMap = new ConcurrentHashMap<>(); String url = "http://" + selectJobInfo.getServiceName() + selectJobInfo.getServiceMethod(); if (!StringUtils.isEmpty(selectJobInfo.getParams())) { paramMap.putAll(JSON.parseObject(selectJobInfo.getParams(), Map.class)); } OAuth2RestTemplate template = ShopSpringContext.getBean(OAuth2RestTemplate.class); // 得到服务鉴权访问token OAuth2AccessToken accessToken = template.getAccessToken(); // 设置请求消息头 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); headers.setBearerAuth(accessToken.toString()); // 得到 RestTemplate 访问的负载均衡对象 RestTemplate restTemplate = ShopSpringContext.getBean("restTemplate", RestTemplate.class); ResponseEntity<Object> responseEntity = restTemplate.postForEntity(url, new HttpEntity<>(paramMap, headers), Object.class); log.info("执行服务调用结束,返回结果 result = {}", JSON.toJSONString(responseEntity)); } else { log.error("未找到执行的定时任务 jobName = {}, jobGroup = {}", jobName, jobGroup); } }
Example 9
Source File: OghamAutoConfigurationSpringPropertiesOnlyTest.java From ogham with Apache License 2.0 | 5 votes |
@Test public void simple() throws MessagingException, IOException { RestTemplate rt = new RestTemplate(); // @formatter:off UriComponentsBuilder builder = UriComponentsBuilder.fromPath(SIMPLE_URL) .scheme("http") .host("localhost") .port(port) .queryParam("subject", "test") .queryParam("to", "[email protected]"); // @formatter:on ResponseEntity<Void> response = rt.postForEntity(builder.toUriString(), new HttpEntity<>("test content"), Void.class); assertEquals("HTTP status should be 201: Created", HttpStatus.CREATED, response.getStatusCode()); AssertEmail.assertEquals(new ExpectedEmail("test", "test content", "[email protected]", "[email protected]"), greenMail.getReceivedMessages()); }
Example 10
Source File: SourceDaoImpl.java From singleton with Eclipse Public License 2.0 | 5 votes |
@Override public boolean sendToRemote(String url, Map<String, Object> requestParam) { LOGGER.info("Send data to remote server [{}] ...", url); LOGGER.info("The request body is: {}", requestParam); boolean result = false; RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); MediaType type = MediaType .parseMediaType("application/json; charset=UTF-8"); headers.setContentType(type); headers.add("Accept", MediaType.APPLICATION_JSON.toString()); JSONObject jsonObj = new JSONObject(requestParam); HttpEntity<String> formEntity = new HttpEntity<String>( jsonObj.toString(), headers); try { ResponseEntity<GRMResponseDTO> responseEntity = restTemplate .postForEntity(url, formEntity, GRMResponseDTO.class); GRMResponseDTO gRMResponseDTO = responseEntity.getBody(); if (gRMResponseDTO.getStatus() == GRMAPIResponseStatus.CREATED .getCode()) { result = true; LOGGER.info("The request has successed, the result: {} {}", gRMResponseDTO.getStatus(), gRMResponseDTO.getResult()); } else { LOGGER.info("The request has failed, the response code: {} reason: {}", + gRMResponseDTO.getStatus(), gRMResponseDTO.getErrorMessage()); } } catch (Exception e) { result = false; } return result; }
Example 11
Source File: RestTemplateLoggingLiveTest.java From tutorials with MIT License | 5 votes |
@Test public void givenHttpClientConfiguration_whenSendGetForRequestEntity_thenRequestResponseFullLog() { RestTemplate restTemplate = new RestTemplate(); restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory()); final ResponseEntity<String> response = restTemplate.postForEntity(baseUrl + "/persons", "my request body", String.class); assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); }
Example 12
Source File: ApiService.java From tutorials with MIT License | 5 votes |
public ResponseEntity<String> postCall(String url, String requestBody) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.set("Authorization", "Bearer "+controller.getManagementApiToken()); HttpEntity<String> request = new HttpEntity<String>(requestBody, headers); RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> result = restTemplate.postForEntity(url, request, String.class); return result; }
Example 13
Source File: MultipartFileUploadClient.java From tutorials with MIT License | 5 votes |
private static void uploadMultipleFile() throws IOException { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.MULTIPART_FORM_DATA); MultiValueMap<String, Object> body = new LinkedMultiValueMap<>(); body.add("files", getTestFile()); body.add("files", getTestFile()); body.add("files", getTestFile()); HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers); String serverUrl = "http://localhost:8082/spring-rest/fileserver/multiplefileupload/"; RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> response = restTemplate.postForEntity(serverUrl, requestEntity, String.class); System.out.println("Response code: " + response.getStatusCode()); }
Example 14
Source File: MultipartFileUploadClient.java From tutorials with MIT License | 5 votes |
private static void uploadSingleFile() throws IOException { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.MULTIPART_FORM_DATA); MultiValueMap<String, Object> body = new LinkedMultiValueMap<>(); body.add("file", getTestFile()); HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers); String serverUrl = "http://localhost:8082/spring-rest/fileserver/singlefileupload/"; RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> response = restTemplate.postForEntity(serverUrl, requestEntity, String.class); System.out.println("Response code: " + response.getStatusCode()); }
Example 15
Source File: StudioWorkspaceResourceHandler.java From bonita-ui-designer with GNU General Public License v2.0 | 5 votes |
protected ResponseEntity<String> doPost(final Path filePath, WorkspaceResourceEvent actionEvent) { if (actionEvent == null) { throw new IllegalArgumentException("actionEvent is null"); } if (restClient.isConfigured()) { final String url = createPostURL(actionEvent); RestTemplate restTemplate = restClient.getRestTemplate(); return restTemplate.postForEntity(URI.create(url), filePath != null ? filePath.toString() : null, String.class); } return new ResponseEntity<>(HttpStatus.SERVICE_UNAVAILABLE); }
Example 16
Source File: ComposerService.java From cubeai with Apache License 2.0 | 5 votes |
private ResponseEntity<String> apiGateway(String url, String requestBody, MultiValueMap<String,String> requestHeader) { logger.debug("Start API forwarding"); try { HttpEntity<String> httpEntity = new HttpEntity<>(requestBody, requestHeader); RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8"))); // 直接使用RestTemplate的POST方法时,字符串默认使用“ISO-8859-1”编码,需要转换 ResponseEntity<String> response = restTemplate.postForEntity(url, httpEntity, String.class); return ResponseEntity.status(response.getStatusCodeValue()).body(response.getBody()); } catch(HttpClientErrorException e) { return ResponseEntity.status(e.getStatusCode()).body(e.getResponseBodyAsString()); } }
Example 17
Source File: AppAbstractComponentSMO.java From MicroCommunity with Apache License 2.0 | 4 votes |
/** * 小程序支付统一下单 */ private Map<String, String> java110UnifieldOrder(RestTemplate outRestTemplate, String feeName, String orderNum, String tradeType, double payAmount, String openid, SmallWeChatDto smallWeChatDto) throws Exception { //封装参数 SortedMap<String, String> paramMap = new TreeMap<String, String>(); paramMap.put("appid", smallWeChatDto.getAppId()); paramMap.put("mch_id", smallWeChatDto.getMchId()); paramMap.put("nonce_str", PayUtil.makeUUID(32)); paramMap.put("body", "HC智慧家园-" + feeName); paramMap.put("out_trade_no", orderNum); paramMap.put("total_fee", PayUtil.moneyToIntegerStr(payAmount)); paramMap.put("spbill_create_ip", PayUtil.getLocalIp()); paramMap.put("notify_url", wechatAuthProperties.getWxNotifyUrl()); paramMap.put("trade_type", tradeType); paramMap.put("openid", openid); String paySwitch = MappingCache.getValue(DOMAIN_WECHAT_PAY, WECHAT_SERVICE_PAY_SWITCH); if (WECHAT_SERVICE_PAY_SWITCH_ON.equals(paySwitch)) { paramMap.put("appid", MappingCache.getValue(DOMAIN_WECHAT_PAY, WECHAT_SERVICE_APP_ID)); //服务商appid,是服务商注册时公众号的id paramMap.put("mch_id", MappingCache.getValue(DOMAIN_WECHAT_PAY, WECHAT_SERVICE_MCH_ID)); //服务商商户号 paramMap.put("sub_appid", smallWeChatDto.getAppId());//起调小程序appid paramMap.put("sub_mch_id", smallWeChatDto.getMchId());//起调小程序的商户号 paramMap.put("sub_openid", openid); paramMap.remove("openid"); } paramMap.put("sign", PayUtil.createSign(paramMap, smallWeChatDto.getPayPassword())); //转换为xml String xmlData = PayUtil.mapToXml(paramMap); logger.debug("调用支付统一下单接口" + xmlData); ResponseEntity<String> responseEntity = outRestTemplate.postForEntity( wechatAuthProperties.getWxPayUnifiedOrder(), xmlData, String.class); logger.debug("统一下单返回" + responseEntity); //请求微信后台,获取预支付ID if (responseEntity.getStatusCode() != HttpStatus.OK) { throw new IllegalArgumentException("支付失败" + responseEntity.getBody()); } return PayUtil.xmlStrToMap(responseEntity.getBody()); }
Example 18
Source File: GitResource.java From jhipster-online with Apache License 2.0 | 4 votes |
/** * Saves the callback code returned by the OAuth2 authentication. */ @PostMapping("/{gitProvider}/save-token") @Secured(AuthoritiesConstants.USER) public @ResponseBody ResponseEntity saveToken(@PathVariable String gitProvider, @RequestBody String code) { try { RestTemplate restTemplate = new RestTemplate(); String url; GitProvider gitProviderEnum; GitAccessTokenRequest request = new GitAccessTokenRequest(); switch (gitProvider.toLowerCase()) { case GITHUB: url = applicationProperties.getGithub().getHost() + "/login/oauth/access_token"; gitProviderEnum = GitProvider.GITHUB; request.setClient_id(applicationProperties.getGithub().getClientId()); request.setClient_secret(applicationProperties.getGithub().getClientSecret()); request.setCode(code); break; case GITLAB: url = applicationProperties.getGitlab().getHost() + "/oauth/token"; gitProviderEnum = GitProvider.GITLAB; request.setClient_id(applicationProperties.getGitlab().getClientId()); request.setClient_secret(applicationProperties.getGitlab().getClientSecret()); request.setGrant_type("authorization_code"); request.setRedirect_uri(applicationProperties.getGitlab().getRedirectUri()); request.setCode(code); break; default: return new ResponseEntity<>("Unknown git provider: " + gitProvider, HttpStatus .INTERNAL_SERVER_ERROR); } HttpHeaders headers = new HttpHeaders(); headers.add("user-agent", "Mozilla/5.0 (X11; Linux x86_64; rv:72.0) Gecko/20100101 Firefox/72.0"); HttpEntity<GitAccessTokenRequest> entity = new HttpEntity<>(request, headers); ResponseEntity<GitAccessTokenResponse> response = restTemplate.postForEntity(url, entity, GitAccessTokenResponse.class); this.userService.saveToken(response.getBody().getAccess_token(), gitProviderEnum); } catch (Exception e) { log.error("OAuth2 token could not saved: {}", e); return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); } return new ResponseEntity<>(HttpStatus.CREATED); }
Example 19
Source File: ItemSetControllerTest.java From apollo with Apache License 2.0 | 4 votes |
@Test @Sql(scripts = "/controller/test-itemset.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD) @Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD) public void testItemSetDeleted() { String appId = "someAppId"; AppDTO app = restTemplate.getForObject("http://localhost:" + port + "/apps/" + appId, AppDTO.class); ClusterDTO cluster = restTemplate.getForObject( "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/default", ClusterDTO.class); NamespaceDTO namespace = restTemplate.getForObject("http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/" + cluster.getName() + "/namespaces/application", NamespaceDTO.class); Assert.assertEquals("someAppId", app.getAppId()); Assert.assertEquals("default", cluster.getName()); Assert.assertEquals("application", namespace.getNamespaceName()); ItemChangeSets createChangeSet = new ItemChangeSets(); createChangeSet.setDataChangeLastModifiedBy("created"); RestTemplate createdTemplate = (new TestRestTemplate()).getRestTemplate(); createdTemplate.setMessageConverters(restTemplate.getMessageConverters()); int createdSize = 3; for (int i = 0; i < createdSize; i++) { ItemDTO item = new ItemDTO(); item.setNamespaceId(namespace.getId()); item.setKey("key_" + i); item.setValue("created_value_" + i); createChangeSet.addCreateItem(item); } ResponseEntity<Void> response = createdTemplate.postForEntity( "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/" + cluster.getName() + "/namespaces/" + namespace.getNamespaceName() + "/itemset", createChangeSet, Void.class); Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); ItemDTO[] items = restTemplate.getForObject( "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/" + cluster.getName() + "/namespaces/" + namespace.getNamespaceName() + "/items", ItemDTO[].class); ItemChangeSets deleteChangeSet = new ItemChangeSets(); deleteChangeSet.setDataChangeLastModifiedBy("deleted"); RestTemplate deletedTemplate = (new TestRestTemplate()).getRestTemplate(); deletedTemplate.setMessageConverters(restTemplate.getMessageConverters()); int deletedSize = 1; for (int i = 0; i < deletedSize; i++) { items[i].setValue("deleted_value_" + i); deleteChangeSet.addDeleteItem(items[i]); } response = deletedTemplate.postForEntity( "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/" + cluster.getName() + "/namespaces/" + namespace.getNamespaceName() + "/itemset", deleteChangeSet, Void.class); Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); List<Item> savedItems = itemRepository.findByNamespaceIdOrderByLineNumAsc(namespace.getId()); Assert.assertEquals(createdSize - deletedSize, savedItems.size()); Item item0 = savedItems.get(0); Assert.assertEquals("key_1", item0.getKey()); Assert.assertEquals("created_value_1", item0.getValue()); Assert.assertEquals("created", item0.getDataChangeCreatedBy()); Assert.assertNotNull(item0.getDataChangeCreatedTime()); }
Example 20
Source File: OneRecordingServerTest.java From kurento-java with Apache License 2.0 | 3 votes |
protected void uploadFileWithPOST(String uploadURL, File fileToUpload) throws FileNotFoundException, IOException { RestTemplate template = new RestTemplate(); ByteArrayOutputStream fileBytes = new ByteArrayOutputStream(); IOUtils.copy(new FileInputStream(fileToUpload), fileBytes); ResponseEntity<String> entity = template.postForEntity(uploadURL, fileBytes.toByteArray(), String.class); assertEquals("Returned response: " + entity.getBody(), HttpStatus.OK, entity.getStatusCode()); }