Java Code Examples for org.springframework.web.client.RestTemplate#exchange()
The following examples show how to use
org.springframework.web.client.RestTemplate#exchange() .
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: GitlabDataGrabber.java From Refactoring-Bot with MIT License | 6 votes |
/** * This method deletes a repository from GitLab. * * @param gitConfig * @throws URISyntaxException * @throws GitLabAPIException */ public void deleteRepository(GitConfiguration gitConfig) throws URISyntaxException, GitLabAPIException { String originalRepo = gitConfig.getRepoApiLink(); String forkRepo = gitConfig.getForkApiLink(); // Never delete the original repository if (originalRepo.equals(forkRepo)) { return; } // Read URI from configuration URI repoUri = createURIFromApiLink(gitConfig.getForkApiLink()); RestTemplate rest = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.set("User-Agent", USER_AGENT); headers.set(TOKEN_HEADER, gitConfig.getBotToken()); HttpEntity<String> entity = new HttpEntity<>("parameters", headers); try { // Send request to the GitLab-API rest.exchange(repoUri, HttpMethod.DELETE, entity, String.class); } catch (RestClientException r) { throw new GitLabAPIException("Could not delete repository from GitLab!", r); } }
Example 2
Source File: RestTemplateTest.java From spring-tutorials with Apache License 2.0 | 6 votes |
@Test public void test_GetHeaders() { baseUrl=baseUrl+"/list"; RestTemplate restTemplate = new RestTemplate(); ParameterizedTypeReference<List<String>> listOfString = new ParameterizedTypeReference<List<String>>() {}; ResponseEntity<List<String>> response= restTemplate.exchange(baseUrl,HttpMethod.GET,null, listOfString); HttpHeaders headers = response.getHeaders(); MediaType contentType = headers.getContentType(); long date = headers.getDate(); List<String> getOrDefault = headers.getOrDefault("X-Forwarded", Collections.singletonList("Does not exists")); HttpStatus status = response.getStatusCode(); notNull(headers); notNull(contentType); notNull(date); notNull(getOrDefault); isTrue(status == HttpStatus.OK); }
Example 3
Source File: ServiceCenterExample.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
public static void main(String[] args) throws Exception { RestTemplate template = new RestTemplate(); template.getMessageConverters().add(new MappingJackson2HttpMessageConverter()); MultiValueMap<String, String> headers = new LinkedMultiValueMap<>(); headers.add("X-Tenant-Name", "default"); RequestEntity<String> requestEntity = new RequestEntity<String>(headers, HttpMethod.GET, new URI("http://127.0.0.1:9980/registry/v3/microservices")); ResponseEntity<String> stringResponseEntity = template.exchange(requestEntity, String.class); System.out.println(stringResponseEntity.getBody()); ResponseEntity<MicroserviceArray> microseriveResponseEntity = template .exchange(requestEntity, MicroserviceArray.class); MicroserviceArray microserives = microseriveResponseEntity.getBody(); System.out.println(microserives.getServices().get(1).getServiceId()); // instance headers.add("X-ConsumerId", microserives.getServices().get(1).getServiceId()); requestEntity = new RequestEntity<String>(headers, HttpMethod.GET, new URI("http://127.0.0.1:9980/registry/v3/microservices/" + microserives.getServices().get(1).getServiceId() + "/instances")); ResponseEntity<String> microserviceInstanceResponseEntity = template.exchange(requestEntity, String.class); System.out.println(microserviceInstanceResponseEntity.getBody()); }
Example 4
Source File: OAuth2Test.java From oauth2-server with MIT License | 6 votes |
public String refreshToken(String refresh_token) throws IOException { String url = issuerUrl + "/oauth/token"; RestTemplate client = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); // 请勿轻易改变此提交方式,大部分的情况下,提交方式都是表单提交 headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); // 封装参数,千万不要替换为Map与HashMap,否则参数无法传递 MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); // 也支持中文 params.add("client_id", "SampleClientId"); params.add("client_secret", "tgb.258"); params.add("grant_type", "refresh_token"); params.add("refresh_token", refresh_token); HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers); // 执行HTTP请求 ResponseEntity<String> response = client.exchange(url, HttpMethod.POST, requestEntity, String.class); String jsonString = response.getBody(); log.info("refreshToken:" + jsonString); Map<String, String> result = JsonUtil.jsonStringToObject(response.getBody(), new TypeReference<Map<String, String>>() { }); // 输出结果 return result.get("access_token"); }
Example 5
Source File: OghamAutoConfigurationSpringPropertiesOnlyTest.java From ogham with Apache License 2.0 | 6 votes |
@Test public void freemarker() throws MessagingException, IOException { RestTemplate rt = new RestTemplate(); // @formatter:off UriComponentsBuilder builder = UriComponentsBuilder.fromPath(FREEMARKER_URL) .scheme("http") .host("localhost") .port(port) .queryParam("subject", "test") .queryParam("template", "register-freemarker.html") .queryParam("to", "[email protected]"); RequestEntity<NestedBean> request = RequestEntity. post(builder.build().toUri()). contentType(MediaType.APPLICATION_JSON). body(new NestedBean(new SimpleBean("foo", 42))); // @formatter:on ResponseEntity<Void> response = rt.exchange(request, Void.class); assertEquals("HTTP status should be 201: Created", HttpStatus.CREATED, response.getStatusCode()); AssertEmail.assertEquals( new ExpectedEmail("test", new ExpectedContent(getClass().getResourceAsStream("/expected/spring/register_foo_42.html"), "text/html.*"), "[email protected]", "[email protected]"), greenMail.getReceivedMessages()); }
Example 6
Source File: UserDashboard.java From OAuth-2.0-Cookbook with MIT License | 6 votes |
private void tryToGetUserProfile(ModelAndView mv, String token) { RestTemplate restTemplate = new RestTemplate(); MultiValueMap<String, String> headers = new LinkedMultiValueMap<>(); headers.add("Authorization", "Bearer " + token); String endpoint = "http://localhost:8080/api/profile"; try { RequestEntity<Object> request = new RequestEntity<>( headers, HttpMethod.GET, URI.create(endpoint)); ResponseEntity<UserProfile> userProfile = restTemplate.exchange(request, UserProfile.class); if (userProfile.getStatusCode().is2xxSuccessful()) { mv.addObject("profile", userProfile.getBody()); } else { throw new RuntimeException("it was not possible to retrieve user profile"); } } catch (HttpClientErrorException e) { throw new RuntimeException("it was not possible to retrieve user profile"); } }
Example 7
Source File: Rest.java From WeEvent with Apache License 2.0 | 6 votes |
public static void main(String[] args) { System.out.println("This is WeEvent restful sample."); try { SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); RestTemplate rest = new RestTemplate(requestFactory); // ensure topic exist "com.weevent.test" String topic = "com.weevent.test"; ResponseEntity<BaseResponse<Boolean>> rsp = rest.exchange("http://localhost:7000/weevent-broker/rest/open?topic={topic}&groupId={groupId}", HttpMethod.GET, null, new ParameterizedTypeReference<BaseResponse<Boolean>>() { }, topic, WeEvent.DEFAULT_GROUP_ID); System.out.println(rsp.getBody().getData()); // publish event to topic "com.weevent.test" SendResult sendResult = rest.getForEntity("http://localhost:7000/weevent-broker/rest/publish?topic={topic}&groupId={groupId}&content={content}", SendResult.class, topic, WeEvent.DEFAULT_GROUP_ID, "hello WeEvent".getBytes(StandardCharsets.UTF_8)).getBody(); System.out.println(sendResult); } catch (RestClientException e) { e.printStackTrace(); } }
Example 8
Source File: OghamAutoConfigurationOghamPropertiesPrecedenceTest.java From ogham with Apache License 2.0 | 6 votes |
@Test public void thymeleaf() throws MessagingException, IOException { RestTemplate rt = new RestTemplate(); // @formatter:off UriComponentsBuilder builder = UriComponentsBuilder.fromPath(THYMELEAF_URL) .scheme("http") .host("localhost") .port(port) .queryParam("subject", "test") .queryParam("template", "register-thymeleaf") .queryParam("to", "[email protected]"); RequestEntity<NestedBean> request = RequestEntity. post(builder.build().toUri()). contentType(MediaType.APPLICATION_JSON). body(new NestedBean(new SimpleBean("foo", 42))); // @formatter:on ResponseEntity<Void> response = rt.exchange(request, Void.class); assertEquals("HTTP status should be 201: Created", HttpStatus.CREATED, response.getStatusCode()); AssertEmail.assertEquals( new ExpectedEmail("test", new ExpectedContent(getClass().getResourceAsStream("/expected/ogham/register_foo_42.html"), "text/html.*"), "[email protected]", "[email protected]"), greenMail.getReceivedMessages()); }
Example 9
Source File: GithubDataGrabber.java From Refactoring-Bot with MIT License | 5 votes |
/** * This method deletes a repository from Github. * * @param gitConfig * @throws URISyntaxException * @throws GitHubAPIException */ public void deleteRepository(GitConfiguration gitConfig) throws URISyntaxException, GitHubAPIException { String originalRepo = gitConfig.getRepoApiLink(); String forkRepo = gitConfig.getForkApiLink(); // Never delete the original repository if (originalRepo.equals(forkRepo)) { return; } // Read URI from configuration URI configUri = createURIFromApiLink(gitConfig.getForkApiLink()); // Build URI UriComponentsBuilder apiUriBuilder = UriComponentsBuilder.newInstance().scheme(configUri.getScheme()) .host(configUri.getHost()).path(configUri.getPath()); apiUriBuilder.queryParam("access_token", gitConfig.getBotToken()); URI repoUri = apiUriBuilder.build().encode().toUri(); RestTemplate rest = new RestTemplate(); try { // Send request to the Github-API rest.exchange(repoUri, HttpMethod.DELETE, null, String.class); } catch (RestClientException r) { throw new GitHubAPIException("Could not delete repository from Github!", r); } }
Example 10
Source File: RestRequestTandemUseSpringRest.java From activiti-in-action-codes with Apache License 2.0 | 5 votes |
/** * 查询全部流程 * * @throws java.io.IOException */ private static void queryDeployment() { /*RestClient restTemplate = newRestClient(); String forObject = restTemplate.getForObject(BASE_REST_URI + "repository/deployments", String.class); System.out.println(forObject);*/ RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> exchange = restTemplate.exchange (BASE_REST_URI + "repository/deployments", HttpMethod.GET, new HttpEntity<Object>(createHeaders("kermit", "kermit")), String.class); String body = exchange.getBody(); System.out.println(body); }
Example 11
Source File: RandomHandlerIntegrationTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void random() throws Throwable { // TODO: fix Reactor support RestTemplate restTemplate = new RestTemplate(); byte[] body = randomBytes(); RequestEntity<byte[]> request = RequestEntity.post(new URI("http://localhost:" + port)).body(body); ResponseEntity<byte[]> response = restTemplate.exchange(request, byte[].class); assertNotNull(response.getBody()); assertEquals(RESPONSE_SIZE, response.getHeaders().getContentLength()); assertEquals(RESPONSE_SIZE, response.getBody().length); }
Example 12
Source File: WriteOnlyHandlerIntegrationTests.java From spring-analysis-note with MIT License | 5 votes |
@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()); }
Example 13
Source File: TWBTranslationServiceTest.java From AIDR with GNU Affero General Public License v3.0 | 5 votes |
public void testSendEncodedDocument() throws Exception { String filename = "TWB_Source_"+System.currentTimeMillis()+".csv"; //decide whether its better to send file or content String content = "被害のダウ"; byte[] bytes = content.getBytes(StandardCharsets.UTF_8); final String url=BASE_URL+"/documents"; HttpHeaders requestHeaders=new HttpHeaders(); requestHeaders.add("X-Proz-API-Key", API_KEY); requestHeaders.setContentType(new MediaType("multipart","form-data")); RestTemplate restTemplate=new RestTemplate(); restTemplate.getMessageConverters() .add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8)); restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter()); LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>(); map.add("document", bytes); map.add("name", "translation_source.csv"); HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<LinkedMultiValueMap<String, Object>>( map, requestHeaders); ResponseEntity<Map> result = restTemplate.exchange(url, HttpMethod.POST, requestEntity, Map.class); Map resultMap = result.getBody(); String download_Link = (String)resultMap.get("download_link"); String returnedDocumentContent = getTranslationDocumentContent(download_Link) ; assert (returnedDocumentContent.equals(content)); }
Example 14
Source File: ApplicationTests.java From Microservices-Building-Scalable-Software with MIT License | 5 votes |
@Test public void testSecureService() { String plainCreds = "guest:guest123"; HttpHeaders headers = new HttpHeaders(); headers.add("Authorization", "Basic " + new String(Base64.encode(plainCreds.getBytes()))); HttpEntity<String> request = new HttpEntity<String>(headers); RestTemplate restTemplate = new RestTemplate(); ResponseEntity<Greet> response = restTemplate.exchange("http://localhost:8080", HttpMethod.GET, request, Greet.class); Assert.assertEquals("Hello World!", response.getBody().getMessage()); }
Example 15
Source File: MailLocalhostTest.java From mail-micro-service with Apache License 2.0 | 5 votes |
@Test public void testSendAttachmentMailLocal() throws Throwable { File folder = new File("F://"); if (!folder.exists() || !folder.isDirectory()) { FileUtils.forceMkdir(folder); } File attachmentFile = new File(folder, "1.txt"); if (attachmentFile.exists() && attachmentFile.isFile()) { FileUtils.forceDelete(attachmentFile); } FileUtils.writeStringToFile(attachmentFile, "hello \r\n mail \r\n" + RandomStringUtils.random(10), "utf8"); attachmentFile.createNewFile(); MultiValueMap<String, Object> param = new LinkedMultiValueMap<String, Object>(); param.add("to", TEST_MAIL); param.add("title", RandomStringUtils.random(5)); param.add("content", RandomStringUtils.random(256)); param.add("attachmentName", RandomStringUtils.random(4) + ".txt"); FileSystemResource resource = new FileSystemResource(attachmentFile); param.add("attachmentFile", resource); HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(param); RestTemplate rest = new RestTemplate(); ResponseEntity<Boolean> response = rest.exchange(MAIL_URL, HttpMethod.POST, httpEntity, Boolean.class); assertTrue(response.getBody()); }
Example 16
Source File: GithubUtil.java From c4sg-services with MIT License | 5 votes |
public static List<Stat.Author> getContributorsByCommitsDesc() throws IOException { RestTemplate restTemplate = new RestTemplate(); ResponseEntity<Stat[]> exchange = restTemplate. exchange("https://api.github.com/repos/" + githubUsername + "/" + githubReponame + "/stats/contributors", HttpMethod.GET, null, Stat[].class); Stat[] stats = exchange.getBody(); List<Stat.Author> contributors = new ArrayList<>(stats.length); for (Stat s : stats) { Stat.Author author = s.getAuthor(); author.setCommits(s.getTotal()); contributors.add(0, author); } return contributors; }
Example 17
Source File: RangerSecurityServiceConnector.java From egeria with Apache License 2.0 | 5 votes |
private RangerTag createRangerTag(RangerTag rangerTag) { String createTagURL = getRangerURL(SERVICE_TAGS); String body = getBody(rangerTag); RestTemplate restTemplate = new RestTemplate(); HttpEntity<String> entity = new HttpEntity<>(body, getHttpHeaders()); try { restTemplate.exchange(createTagURL, HttpMethod.POST, entity, RangerTag.class); return rangerTag; } catch (HttpStatusCodeException exception) { log.debug("Unable to create a security tag {}", rangerTag); } return rangerTag; }
Example 18
Source File: AuthServiceImpl.java From redtorch with MIT License | 4 votes |
@Override public boolean login(String username, String password) { if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) { return false; } JSONObject reqDataJsonObject = new JSONObject(); reqDataJsonObject.put("username", username); reqDataJsonObject.put("password", password); RestTemplate rest = new RestTemplate(); HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.add("Content-Type", "application/json"); requestHeaders.add("Accept", "*/*"); HttpEntity<String> requestEntity = new HttpEntity<String>(reqDataJsonObject.toJSONString(), requestHeaders); loginStatus = false; responseHttpHeaders = null; this.username = ""; try { ResponseEntity<String> responseEntity = rest.exchange(loginUri, HttpMethod.POST, requestEntity, String.class); System.out.println(responseEntity.toString()); if (responseEntity.getStatusCode().is2xxSuccessful()) { JSONObject resultJSONObject = JSON.parseObject(responseEntity.getBody()); if (resultJSONObject.getBooleanValue("status")) { JSONObject voData = resultJSONObject.getJSONObject("voData"); nodeId = voData.getInteger("recentlyNodeId"); operatorId = voData.getString("operatorId"); this.username = username; loginStatus = true; responseHttpHeaders = responseEntity.getHeaders(); logger.info("登录成功!"); return true; } else { logger.error("登录失败!服务器返回错误!"); return false; } } else { logger.info("登录失败!"); return false; } } catch (Exception e) { logger.error("登录请求错误!", e); return false; } }
Example 19
Source File: JaxrsClient.java From servicecomb-java-chassis with Apache License 2.0 | 4 votes |
private static void testValidatorSayHiSuccess(RestTemplate template, String cseUrlPrefix) { ResponseEntity<String> responseEntity = template.exchange(cseUrlPrefix + "sayhi/{name}", HttpMethod.PUT, null, String.class, "world"); TestMgr.check(202, responseEntity.getStatusCodeValue()); TestMgr.check("world sayhi", responseEntity.getBody()); }
Example 20
Source File: CodeFirstRestTemplate.java From servicecomb-java-chassis with Apache License 2.0 | 4 votes |
private void testCodeFirstSayHi2(RestTemplate template, String cseUrlPrefix) { ResponseEntity<String> responseEntity = template.exchange(cseUrlPrefix + "sayhi/{name}/v2", HttpMethod.PUT, null, String.class, "world"); TestMgr.check("world sayhi 2", responseEntity.getBody()); }