Java Code Examples for org.springframework.web.client.RestTemplate#postForObject()
The following examples show how to use
org.springframework.web.client.RestTemplate#postForObject() .
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: AuthController.java From tutorials with MIT License | 7 votes |
public String getManagementApiToken() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); JSONObject requestBody = new JSONObject(); requestBody.put("client_id", config.getManagementApiClientId()); requestBody.put("client_secret", config.getManagementApiClientSecret()); requestBody.put("audience", "https://dev-example.auth0.com/api/v2/"); requestBody.put("grant_type", config.getGrantType()); HttpEntity<String> request = new HttpEntity<String>(requestBody.toString(), headers); RestTemplate restTemplate = new RestTemplate(); HashMap<String, String> result = restTemplate.postForObject(AUTH0_TOKEN_URL, request, HashMap.class); return result.get("access_token"); }
Example 2
Source File: KafkaStreamsInteractiveQuerySample.java From spring-cloud-stream-samples with Apache License 2.0 | 6 votes |
@RequestMapping("/charts/top-five") @SuppressWarnings("unchecked") public List<SongPlayCountBean> topFive(@RequestParam(value="genre") String genre) { HostInfo hostInfo = interactiveQueryService.getHostInfo(KafkaStreamsInteractiveQuerySample.TOP_FIVE_SONGS_STORE, KafkaStreamsInteractiveQuerySample.TOP_FIVE_KEY, new StringSerializer()); if (interactiveQueryService.getCurrentHostInfo().equals(hostInfo)) { logger.info("Top Five songs request served from same host: " + hostInfo); return topFiveSongs(KafkaStreamsInteractiveQuerySample.TOP_FIVE_KEY, KafkaStreamsInteractiveQuerySample.TOP_FIVE_SONGS_STORE); } else { //find the store from the proper instance. logger.info("Top Five songs request served from different host: " + hostInfo); RestTemplate restTemplate = new RestTemplate(); return restTemplate.postForObject( String.format("http://%s:%d/%s", hostInfo.host(), hostInfo.port(), "charts/top-five?genre=Punk"), "punk", List.class); } }
Example 3
Source File: RegistryService.java From SkaETL with Apache License 2.0 | 6 votes |
private void triggerAction(ConsumerState consumerState, String action, StatusProcess statusIfOk, StatusProcess statusIfKo) { boolean hasErrors = consumerState.getStatusProcess() == StatusProcess.ERROR; for (String workerFQDN : consumerState.getRegistryWorkers()) { RegistryWorker worker = workerRepository.findByKey(workerFQDN); log.info("triggering {} on {}", action, consumerState.getProcessDefinition()); try { RestTemplate restTemplate = new RestTemplate(); HttpEntity<ProcessDefinition> request = new HttpEntity<>(consumerState.getProcessDefinition()); restTemplate.postForObject(worker.getBaseUrl() + "/manage/" + action, request, String.class); } catch (RestClientException e) { log.error("an error occured while triggering" + action + " on " + consumerState.getProcessDefinition(), e.getMessage()); hasErrors = true; } } ConsumerState newState; if (!hasErrors) { newState = consumerState.withStatusProcess(statusIfOk); if ("deactivate".equals(statusIfOk)) { newState.getRegistryWorkers().clear(); } } else { newState = consumerState.withStatusProcess(statusIfKo); } consumerStateRepository.save(newState); }
Example 4
Source File: Oauth2ClientTest.java From open-cloud with MIT License | 6 votes |
public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); // restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor) HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap<>(); postParameters.add("client_id","1556153880995"); postParameters.add("client_secret", "ecac8f3b0876469d9d4ebc4dab811f03"); postParameters.add("grant_type", "authorization_code"); postParameters.add("code", "sv0gnx"); postParameters.add("redirect_uri", "http://222.240.195.28:8080/risk-web/a/login"); // 使用客户端的请求头,发起请求 HttpEntity<MultiValueMap<String, Object> > requestEntity = new HttpEntity(postParameters, requestHeaders); String result = restTemplate.postForObject("http://39.106.187.125:8888/auth/oauth/token", requestEntity, String.class); System.out.println(result); }
Example 5
Source File: AccountSampleTest.java From sctalk with Apache License 2.0 | 6 votes |
@Test public void test() { RestTemplate rt = new RestTemplate(); for (int i = 10; i< 100;i++) { System.out.println(i%2); RegistReq req = new RegistReq(); req.setName("" + i); req.setSex(i%2); req.setPhone("0000" + i); req.setPassword(SecurityUtils.getInstance().EncryptPass("" + i)); req.setEmail(i + "@hifipi.com"); BaseModel res = rt.postForObject("http://tt.hifipi.com/regist", req, BaseModel.class); System.out.println(res.getCode()); } }
Example 6
Source File: SpringmvcClient.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
private static void testSpringMvcDefaultValuesJavaPrimitiveRest(RestTemplate template, String microserviceName) { String cseUrlPrefix = "cse://" + microserviceName + "/SpringMvcDefaultValues/"; //default values with primitive String result = template.postForObject(cseUrlPrefix + "/javaprimitiveint", null, String.class); TestMgr.check("Hello 0bobo", result); result = template.postForObject(cseUrlPrefix + "/javaprimitivenumber", null, String.class); TestMgr.check("Hello 0.0false", result); result = template.postForObject(cseUrlPrefix + "/javaprimitivestr", null, String.class); TestMgr.check("Hello", result); result = template.postForObject(cseUrlPrefix + "/javaprimitivecomb", null, String.class); TestMgr.check("Hello nullnull", result); result = template.postForObject(cseUrlPrefix + "/allprimitivetypes", null, String.class); TestMgr.check("Hello false,\0,0,0,0,0,0.0,0.0,null", result); }
Example 7
Source File: ContaAzulService.java From api-examples with Apache License 2.0 | 5 votes |
public Token getContaAzulTokens(String url) throws IOException { HttpEntity<MultiValueMap<String, String>> httpEntity; httpEntity = getTokenRequestConfig(); RestTemplate restTemplate = new RestTemplate(); Token token = restTemplate.postForObject(url, httpEntity, Token.class); return token; }
Example 8
Source File: CodeFirstRestTemplate.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
private void testCodeFirstAddDate(RestTemplate template, String cseUrlPrefix) { Map<String, Object> body = new HashMap<>(); Date date = new Date(); body.put("date", date); int seconds = 1; Date result = template.postForObject(cseUrlPrefix + "addDate?seconds={seconds}", body, Date.class, seconds); TestMgr.check(new Date(date.getTime() + seconds * 1000), result); }
Example 9
Source File: CodeFirstRestTemplateSpringmvc.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
private String testRestTemplateUpload(RestTemplate template, String cseUrlPrefix, File file1, File someFile) { MultiValueMap<String, Object> map = new LinkedMultiValueMap<>(); map.add("file1", new FileSystemResource(file1)); map.add("someFile", new FileSystemResource(someFile)); return template.postForObject( cseUrlPrefix + "/upload", new HttpEntity<MultiValueMap<String, Object>>(map), String.class); }
Example 10
Source File: ProcessServiceHTTP.java From SkaETL with Apache License 2.0 | 5 votes |
public void saveOrUpdate(ProcessConsumer processConsumer) { log.info("Call saveOrUpdate {}", processConsumer); RestTemplate restTemplate = new RestTemplate(); HttpEntity<ProcessConsumer> request = new HttpEntity<>(processConsumer); try { restTemplate.postForObject(generatorConfiguration.getBackend() + "/process/save", request, String.class); } catch (Exception e) { log.error("status {}", e); } }
Example 11
Source File: CodeFirstRestTemplate.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
private void testCodeFirstBytes(RestTemplate template, String cseUrlPrefix) { byte[] body = new byte[] {0, 1, 2}; byte[] result = template.postForObject(cseUrlPrefix + "bytes", body, byte[].class); TestMgr.check(3, result.length); TestMgr.check(1, result[0]); TestMgr.check(1, result[1]); TestMgr.check(2, result[2]); }
Example 12
Source File: GluonService.java From gluon-samples with BSD 3-Clause "New" or "Revised" License | 5 votes |
private String addMessage(String objectIdentifier) { JsonObject payload = Json.createObjectBuilder() .add("v", "") .build(); RestTemplate restTemplate = new RestTemplate(); return restTemplate.postForObject(gclUrl + "/3/data/enterprise/object/" + objectIdentifier + "/add", getHeaders(payload.toString()), String.class); }
Example 13
Source File: APISteps.java From OpenESPI-DataCustodian-java with Apache License 2.0 | 5 votes |
@Ignore @When("^I POST \\/espi\\/1_1\\/resource\\/RetailCustomer\\/\\{RetailCustomerID\\}\\/UsagePoint$") public void I_POST_espi_1_1_resource_RetailCustomer_RetailCustomerID_UsagePoint() throws Throwable { RestTemplate rest = new RestTemplate(); String response = rest .postForObject( StepUtils.DATA_CUSTODIAN_BASE_URL + "/espi/1_1/resource/RetailCustomer/1/UsagePoint", "<entry xmlns=\"http://www.w3.org/2005/Atom\">>" + " <id>urn:uuid:97EAEBAD-1214-4A58-A3D4-A16A6DE718E1</id>" + " <published>2012-10-24T00:00:00Z</published>" + " <updated>2012-10-24T00:00:00Z</updated>" + " <link rel=\"self\"" + " href=\"/espi/1_1/resource/RetailCustomer/1/UsagePoint/97EAEBAD-1214-4A58-A3D4-A16A6DE718E1\"/>" + " <link rel=\"up\"" + " href=\"/espi/1_1/resource/RetailCustomer/1/UsagePoint\"/>" + " <link rel=\"related\"" + " href=\"/espi/1_1/resource/RetailCustomer/1/UsagePoint/97EAEBAD-1214-4A58-A3D4-A16A6DE718E1/MeterReading\"/>" + " <link rel=\"related\"" + " href=\"/espi/1_1/resource/RetailCustomer/1/UsagePoint/97EAEBAD-1214-4A58-A3D4-A16A6DE718E1/ElectricPowerUsageSummary\"/>" + " <link rel=\"related\"" + " href=\"/espi/1_1/resource/UsagePoint/01/LocalTimeParameters/01\"/>" + " <title>Created</title>" + " <content>" + " <UsagePoint xmlns=\"http://naesb.org/espi\">" + " <ServiceCategory>" + " <kind>0</kind>" + " </ServiceCategory>" + " </UsagePoint>" + " </content>" + "</entry>", String.class); assertThat(response, is(nullValue())); }
Example 14
Source File: RestTemplateDemoController.java From springbootexamples with Apache License 2.0 | 5 votes |
@Test public void add(){ String uri = "http://localhost:8080/sbe/bootUser"; /*// 使用下面的方式接受不到User参数 // 需要User 声明 @RequestBody User user = new User(); user.setName("ljk2"); user.setAge(19); user.setAddr("addr"); User userResult = restTemplate.postForObject(uri, user, User.class); log.info("添加用户:"+"name:{},age:{}",userResult.getName(),userResult.getAge());*/ //postForEntity 方式获取 //Form表单的都提交方式 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>(); params.add("name", "ljk2"); params.add("age", "19"); params.add("addr", "addr"); RestTemplate restTemplate = new RestTemplate(); HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<MultiValueMap<String, String>>(params,headers); ResponseEntity<User> request = restTemplate.postForEntity(uri, httpEntity,User.class); User user = request.getBody(); log.info("添加用户:"+"name:{},age:{}",user.getName(),user.getAge()); //postForObject 方式获取 User userResult2 = restTemplate.postForObject(uri, httpEntity, User.class); log.info("添加用户:"+"name:{},age:{}",userResult2.getName(),userResult2.getAge()); }
Example 15
Source File: JaxrsClient.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
private static void testValidatorExchangeSuccess(RestTemplate template, String cseUrlPrefix) { Student student = new Student(); student.setName("test"); student.setAge(15); Student result = template.postForObject(cseUrlPrefix + "sayhello", student, Student.class); TestMgr.check("hello test 15", result); }
Example 16
Source File: EmployeeClient.java From tutorials with MIT License | 5 votes |
public void createEmployeesUsingWrapperClass() { RestTemplate restTemplate = new RestTemplate(); List<Employee> newEmployees = new ArrayList<>(); newEmployees.add(new Employee(3, "Intern")); newEmployees.add(new Employee(4, "CEO")); restTemplate.postForObject( "http://localhost:8082/spring-rest/employees/v2/", new EmployeeList(newEmployees), ResponseEntity.class); }
Example 17
Source File: CodeFirstRestTemplateSpringmvc.java From servicecomb-java-chassis with Apache License 2.0 | 4 votes |
@SuppressWarnings("deprecation") // TODO : upgrade to spring 5 will having warning's , we'll fix it later private void testUpload(RestTemplate template, String cseUrlPrefix) throws IOException { String file1Content = "hello world"; File file1 = File.createTempFile("测 试", ".txt"); FileUtils.writeStringToFile(file1, file1Content, StandardCharsets.UTF_8, false); String file2Content = " bonjour"; File someFile = File.createTempFile("upload2", ".txt"); FileUtils.writeStringToFile(someFile, file2Content, StandardCharsets.UTF_8, false); String expect = String.format("%s:%s:%s\n" + "%s:%s:%s", file1.getName(), MediaType.TEXT_PLAIN_VALUE, file1Content, someFile.getName(), MediaType.TEXT_PLAIN_VALUE, file2Content); String result = testRestTemplateUpload(template, cseUrlPrefix, file1, someFile); TestMgr.check(expect, result); MultiValueMap<String, Object> map = new LinkedMultiValueMap<>(); map.add("file1", new FileSystemResource(file1)); result = template.postForObject( cseUrlPrefix + "/upload1", new HttpEntity<MultiValueMap<String, Object>>(map), String.class); result = uploadPartAndFile.fileUpload(new FilePart(null, file1), someFile); TestMgr.check(expect, result); expect = String.format("null:%s:%s\n" + "%s:%s:%s", MediaType.APPLICATION_OCTET_STREAM_VALUE, file1Content, someFile.getName(), MediaType.TEXT_PLAIN_VALUE, file2Content); result = uploadStreamAndResource .fileUpload(new ByteArrayInputStream(file1Content.getBytes(StandardCharsets.UTF_8)), new org.springframework.core.io.PathResource(someFile.getAbsolutePath())); TestMgr.check(expect, result); }
Example 18
Source File: HybridServiceTest.java From chassis with Apache License 2.0 | 4 votes |
@Test public void testHybridService() throws Exception { Map<String, Object> properties = new HashMap<String, Object>(); properties.put("websocket.enabled", "true"); properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("websocket.hostname", "localhost"); properties.put("http.enabled", "true"); properties.put("http.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("http.hostname", "localhost"); AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); StandardEnvironment environment = new StandardEnvironment(); environment.getPropertySources().addFirst(new MapPropertySource("default", properties)); context.setEnvironment(environment); context.register(PropertySourcesPlaceholderConfigurer.class); context.register(TransportConfiguration.class); context.register(TestCombinedService.class); WebSocketClient wsClient = new WebSocketClient(); RestTemplate httpClient = new RestTemplate(); try { context.refresh(); final MessageSerDe serDe = context.getBean(ProtobufMessageSerDe.class); final WebSocketMessageRegistry messageRegistry = context.getBean(WebSocketMessageRegistry.class); messageRegistry.registerType("stuff", TestObject.class); wsClient.start(); httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR)); List<HttpMessageConverter<?>> messageConverters = new ArrayList<>(); for (MessageSerDe messageSerDe : context.getBeansOfType(MessageSerDe.class).values()) { messageConverters.add(new SerDeHttpMessageConverter(messageSerDe)); } messageConverters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8)); httpClient.setMessageConverters(messageConverters); QueuingWebSocketListener webSocket = new QueuingWebSocketListener(serDe, messageRegistry, null); Session session = wsClient.connect(webSocket, new URI("ws://localhost:" + properties.get("websocket.port") + "/protobuf")).get(5000, TimeUnit.MILLISECONDS); Envelope envelope = new Envelope("getStuff", null, null, null); session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope))); TestObject response = webSocket.getResponse(5, TimeUnit.SECONDS); Assert.assertNotNull(response); Assert.assertEquals("stuff", response.value); byte[] rawStuff = serDe.serialize(new TestObject("more stuff")); envelope = new Envelope("setStuff", "stuff", null, ByteBuffer.wrap(rawStuff)); session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope))); response = webSocket.getResponse(5, TimeUnit.SECONDS); Assert.assertNotNull(response); Assert.assertEquals("stuff", response.value); envelope = new Envelope("getStuff", null, null, null); session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope))); response = webSocket.getResponse(5, TimeUnit.SECONDS); Assert.assertNotNull(response); Assert.assertEquals("more stuff", response.value); response = httpClient.getForObject(new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("more stuff", response.value); response = httpClient.postForObject(new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), new TestObject("even more stuff"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("more stuff", response.value); response = httpClient.getForObject(new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("even more stuff", response.value); } finally { try { wsClient.stop(); } finally { context.close(); } } }
Example 19
Source File: OpencpsCallStatisticRestFacadeImpl.java From opencps-v2 with GNU Affero General Public License v3.0 | 4 votes |
protected DossierStatisticModel makeServiceCall(DossierStatisticModel payload) throws UpstreamServiceTimedOutException, UpstreamServiceFailedException { MultiValueMap<String, String> urlQueryParams = new LinkedMultiValueMap<>(); // buildUrlQueryParams(urlQueryParams, payload); String endPoint = Validator.isNotNull(payload.getEndpoint()) ? payload.getEndpoint() : DossierStatisticConfig.get(DossierStatisticConstants.STATISTIC_REPORT_ENDPOINT); HashMap<String, String> urlPathSegments = new HashMap<>(); String url = buildUrl(endPoint, urlPathSegments, urlQueryParams); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add("groupId", Long.toString(payload.getGroupId())); httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED); httpHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>(); params.add(ReportConstants.BETIMESCOUNT, String.valueOf(payload.getBetimesCount())); params.add(ReportConstants.CANCELLEDCOUNT, String.valueOf(payload.getCancelledCount())); params.add(ReportConstants.DENIEDCOUNT, String.valueOf(payload.getDeniedCount())); params.add(ReportConstants.DOMAINCODE, String.valueOf(payload.getDomainCode())); params.add(ReportConstants.DOMAINNAME, String.valueOf(payload.getDomainName())); params.add(ReportConstants.DONECOUNT, String.valueOf(payload.getDoneCount())); params.add(ReportConstants.GOVAGENCYCODE, String.valueOf(payload.getGovAgencyCode())); params.add(ReportConstants.GOVAGENCYNAME, String.valueOf(payload.getGovAgencyName())); params.add(ReportConstants.GROUPAGENCYCODE, String.valueOf(payload.getGroupAgencyCode())); params.add(ReportConstants.INSIDECOUNT, String.valueOf(payload.getInsideCount())); params.add(ReportConstants.INTEROPERATINGCOUNT, String.valueOf(payload.getInteroperatingCount())); params.add(ReportConstants.MONTH, String.valueOf(payload.getMonth())); params.add(ReportConstants.ONEGATECOUNT, String.valueOf(payload.getOnegateCount())); params.add(ReportConstants.ONLINECOUNT, String.valueOf(payload.getOnlineCount())); params.add(ReportConstants.ONTIMECOUNT, String.valueOf(payload.getOntimeCount())); params.add(ReportConstants.ONTIMEPERCENTAGE, String.valueOf(payload.getOntimePercentage())); params.add(ReportConstants.OUTSIDECOUNT, String.valueOf(payload.getOutsideCount())); params.add(ReportConstants.OVERDUECOUNT, String.valueOf(payload.getOverdueCount())); params.add(ReportConstants.OVERTIMECOUNT, String.valueOf(payload.getOvertimeCount())); params.add(ReportConstants.OVERTIMEINSIDE, String.valueOf(payload.getOvertimeInside())); params.add(ReportConstants.OVERTIMEOUTSIDE, String.valueOf(payload.getOvertimeOutside())); params.add(ReportConstants.PAUSINGCOUNT, String.valueOf(payload.getPausingCount())); params.add(ReportConstants.PROCESSCOUNT, String.valueOf(payload.getProcessCount())); params.add(ReportConstants.PROCESSINGCOUNT, String.valueOf(payload.getProcessingCount())); params.add(ReportConstants.RECEIVEDCOUNT, String.valueOf(payload.getReceivedCount())); params.add(ReportConstants.RELEASECOUNT, String.valueOf(payload.getReleaseCount())); params.add(ReportConstants.RELEASINGCOUNT, String.valueOf(payload.getReleasingCount())); params.add(ReportConstants.REMAININGCOUNT, String.valueOf(payload.getRemainingCount())); params.add(ReportConstants.REPORTING, String.valueOf(payload.getReporting())); params.add(ReportConstants.TOTALCOUNT, String.valueOf(payload.getTotalCount())); params.add(ReportConstants.UNDUECOUNT, String.valueOf(payload.getUndueCount())); params.add(ReportConstants.UNRESOLVEDCOUNT, String.valueOf(payload.getUnresolvedCount())); params.add(ReportConstants.WAITINGCOUNT, String.valueOf(payload.getWaitingCount())); params.add(ReportConstants.YEAR, String.valueOf(payload.getYear())); SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); requestFactory.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT); requestFactory.setReadTimeout(DEFAULT_READ_TIMEOUT); RestTemplate restTemplate = new RestTemplate(requestFactory); HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(params, httpHeaders); DossierStatisticModel result = restTemplate.postForObject(url, request, DossierStatisticModel.class); return result; }
Example 20
Source File: ITTracingClientHttpRequestInterceptor.java From brave with Apache License 2.0 | 4 votes |
@Override protected void post(ClientHttpRequestFactory client, String uri, String content) { RestTemplate restTemplate = new RestTemplate(client); restTemplate.setInterceptors(Collections.singletonList(interceptor)); restTemplate.postForObject(url(uri), content, String.class); }