Java Code Examples for org.springframework.http.HttpHeaders#set()
The following examples show how to use
org.springframework.http.HttpHeaders#set() .
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: OAuth2AutoConfigurationTests.java From spring-security-oauth2-boot with Apache License 2.0 | 6 votes |
private void verifyAuthentication(ClientDetails config, HttpStatus finalStatus) { String baseUrl = "http://localhost:" + this.context.getWebServer().getPort(); TestRestTemplate rest = new TestRestTemplate(); // First, verify the web endpoint can't be reached assertEndpointUnauthorized(baseUrl, rest); // Since we can't reach it, need to collect an authorization token HttpHeaders headers = getHeaders(config); String url = baseUrl + "/oauth/token"; JsonNode tokenResponse = rest.postForObject(url, new HttpEntity<>(getBody(), headers), JsonNode.class); String authorizationToken = tokenResponse.findValue("access_token").asText(); String tokenType = tokenResponse.findValue("token_type").asText(); String scope = tokenResponse.findValues("scope").get(0).toString(); assertThat(tokenType).isEqualTo("bearer"); assertThat(scope).isEqualTo("\"read\""); // Now we should be able to see that endpoint. headers.set("Authorization", "BEARER " + authorizationToken); ResponseEntity<String> securedResponse = rest.exchange( new RequestEntity<Void>(headers, HttpMethod.GET, URI.create(baseUrl + "/securedFind")), String.class); assertThat(securedResponse.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(securedResponse.getBody()) .isEqualTo("You reached an endpoint " + "secured by Spring Security OAuth2"); ResponseEntity<String> entity = rest.exchange( new RequestEntity<Void>(headers, HttpMethod.POST, URI.create(baseUrl + "/securedSave")), String.class); assertThat(entity.getStatusCode()).isEqualTo(finalStatus); }
Example 2
Source File: FlowableIdmApplicationSecurityTest.java From flowable-engine with Apache License 2.0 | 6 votes |
private Map<String, TestLink> getEndpointLinks() { String actuatorUrl = "http://localhost:" + serverPort + "/flowable-idm/actuator"; HttpHeaders headers = new HttpHeaders(); headers.set(HttpHeaders.AUTHORIZATION, authorization("test-admin", "test")); HttpEntity<?> request = new HttpEntity<>(headers); ResponseEntity<Map<String, Map<String, TestLink>>> exchange = restTemplate .exchange(actuatorUrl, HttpMethod.GET, request, new ParameterizedTypeReference<Map<String, Map<String, TestLink>>>() { }); Map<String, Map<String, TestLink>> response = exchange.getBody(); assertThat(response) .as("Actuator response") .isNotNull() .containsKeys("_links"); Map<String, TestLink> links = response.get("_links"); assertThat(links.keySet()) .as("Actuator links") .containsExactlyInAnyOrderElementsOf(ACTUATOR_LINKS); return links; }
Example 3
Source File: AsyncRestTemplateIntegrationTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test public void exchangePostCallback() throws Exception { HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.set("MyHeader", "MyValue"); requestHeaders.setContentType(MediaType.TEXT_PLAIN); HttpEntity<String> requestEntity = new HttpEntity<String>(helloWorld, requestHeaders); ListenableFuture<ResponseEntity<Void>> resultFuture = template.exchange(baseUrl + "/{method}", HttpMethod.POST, requestEntity, Void.class, "post"); final URI expected =new URI(baseUrl + "/post/1"); resultFuture.addCallback(new ListenableFutureCallback<ResponseEntity<Void>>() { @Override public void onSuccess(ResponseEntity<Void> result) { assertEquals("Invalid location", expected, result.getHeaders().getLocation()); assertFalse(result.hasBody()); } @Override public void onFailure(Throwable ex) { fail(ex.getMessage()); } }); while (!resultFuture.isDone()) { } }
Example 4
Source File: SampleController.java From wingtips with Apache License 2.0 | 5 votes |
private HttpEntity getHttpEntityWithUserIdHeader() { HttpHeaders headers = new HttpHeaders(); String userId = Tracer.getInstance().getCurrentSpan().getUserId(); if (userIdHeaderKeys.isEmpty() || userId == null) { return new HttpEntity(headers); } headers.set(userIdHeaderKeys.get(0), userId); return new HttpEntity(headers); }
Example 5
Source File: RestTemplateIntegrationTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void exchangePost() throws Exception { HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.set("MyHeader", "MyValue"); requestHeaders.setContentType(MediaType.TEXT_PLAIN); HttpEntity<String> requestEntity = new HttpEntity<String>(helloWorld, requestHeaders); HttpEntity<Void> result = template.exchange(baseUrl + "/{method}", HttpMethod.POST, requestEntity, Void.class, "post"); assertEquals("Invalid location", new URI(baseUrl + "/post/1"), result.getHeaders().getLocation()); assertFalse(result.hasBody()); }
Example 6
Source File: FlowableModelerApplicationSecurityTest.java From flowable-engine with Apache License 2.0 | 5 votes |
@Test public void modelerUserShouldBeAbleToAccessStencilSets() { String stencilsUrl = "http://localhost:" + serverPort + "/flowable-modeler/app/rest/stencil-sets/editor"; HttpHeaders headers = new HttpHeaders(); headers.set(HttpHeaders.COOKIE, rememberMeCookie("modeler", "test-modeler-value")); HttpEntity<?> request = new HttpEntity<>(headers); ResponseEntity<Object> result = restTemplate.exchange(stencilsUrl, HttpMethod.GET, request, Object.class); assertThat(result.getStatusCode()) .as("GET editor stencil-sets") .isEqualTo(HttpStatus.OK); }
Example 7
Source File: RestTemplateTests.java From spring-analysis-note with MIT License | 5 votes |
@Test @SuppressWarnings("rawtypes") public void exchangeParameterizedType() throws Exception { GenericHttpMessageConverter converter = mock(GenericHttpMessageConverter.class); template.setMessageConverters(Collections.<HttpMessageConverter<?>>singletonList(converter)); ParameterizedTypeReference<List<Integer>> intList = new ParameterizedTypeReference<List<Integer>>() {}; given(converter.canRead(intList.getType(), null, null)).willReturn(true); given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); given(converter.canWrite(String.class, String.class, null)).willReturn(true); HttpHeaders requestHeaders = new HttpHeaders(); mockSentRequest(POST, "https://example.com", requestHeaders); List<Integer> expected = Collections.singletonList(42); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.setContentType(MediaType.TEXT_PLAIN); responseHeaders.setContentLength(10); mockResponseStatus(HttpStatus.OK); given(response.getHeaders()).willReturn(responseHeaders); given(response.getBody()).willReturn(new ByteArrayInputStream(Integer.toString(42).getBytes())); given(converter.canRead(intList.getType(), null, MediaType.TEXT_PLAIN)).willReturn(true); given(converter.read(eq(intList.getType()), eq(null), any(HttpInputMessage.class))).willReturn(expected); HttpHeaders entityHeaders = new HttpHeaders(); entityHeaders.set("MyHeader", "MyValue"); HttpEntity<String> requestEntity = new HttpEntity<>("Hello World", entityHeaders); ResponseEntity<List<Integer>> result = template.exchange("https://example.com", POST, requestEntity, intList); 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(); }
Example 8
Source File: FlowableIdmApplicationSecurityTest.java From flowable-engine with Apache License 2.0 | 5 votes |
@Test public void restUserShouldBeUnauthorized() { String authenticateUrl = "http://localhost:" + serverPort + "/flowable-idm/app/rest/admin/groups"; HttpHeaders headers = new HttpHeaders(); headers.set(HttpHeaders.COOKIE, rememberMeCookie("rest", "test-rest-value")); HttpEntity<?> request = new HttpEntity<>(headers); ResponseEntity<Object> result = restTemplate.exchange(authenticateUrl, HttpMethod.GET, request, Object.class); assertThat(result.getStatusCode()) .as("GET App Groups") .isEqualTo(HttpStatus.UNAUTHORIZED); }
Example 9
Source File: RestTemplateTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void exchange() throws Exception { given(converter.canRead(Integer.class, null)).willReturn(true); given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(this.request); HttpHeaders requestHeaders = new HttpHeaders(); given(this.request.getHeaders()).willReturn(requestHeaders); given(converter.canWrite(String.class, null)).willReturn(true); String body = "Hello World"; converter.write(body, null, this.request); given(this.request.execute()).willReturn(response); given(errorHandler.hasError(response)).willReturn(false); Integer expected = 42; HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.setContentType(MediaType.TEXT_PLAIN); responseHeaders.setContentLength(10); given(response.getStatusCode()).willReturn(HttpStatus.OK); given(response.getHeaders()).willReturn(responseHeaders); given(response.getBody()).willReturn(new ByteArrayInputStream(expected.toString().getBytes())); given(converter.canRead(Integer.class, MediaType.TEXT_PLAIN)).willReturn(true); given(converter.read(Integer.class, response)).willReturn(expected); given(converter.read(eq(Integer.class), any(HttpInputMessage.class))).willReturn(expected); given(response.getStatusCode()).willReturn(HttpStatus.OK); HttpStatus status = HttpStatus.OK; given(response.getStatusCode()).willReturn(status); given(response.getStatusText()).willReturn(status.getReasonPhrase()); HttpHeaders entityHeaders = new HttpHeaders(); entityHeaders.set("MyHeader", "MyValue"); HttpEntity<String> requestEntity = new HttpEntity<String>(body, entityHeaders); ResponseEntity<Integer> result = template.exchange("http://example.com", HttpMethod.POST, requestEntity, Integer.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(); }
Example 10
Source File: Resilience4JCircuitBreakerIntegrationTest.java From spring-cloud-circuitbreaker with Apache License 2.0 | 5 votes |
private HttpEntity<String> createEntityWithOptionalDelayHeader( int delayInMilliseconds) { HttpHeaders headers = new HttpHeaders(); if (delayInMilliseconds > 0) { headers.set("delayInMilliseconds", Integer.toString(delayInMilliseconds)); } return new HttpEntity<>(null, headers); }
Example 11
Source File: RestTemplateIntegrationTests.java From java-technology-stack with MIT License | 5 votes |
@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()); }
Example 12
Source File: VaultTokenRenewalAutoConfiguration.java From spring-cloud-services-connector with Apache License 2.0 | 5 votes |
private HttpEntity<Map<String, Long>> buildTokenRenewRequest(String vaultToken, long renewTTL) { Map<String, Long> requestBody = new HashMap<>(); requestBody.put("increment", renewTTL); HttpHeaders headers = new HttpHeaders(); headers.set("X-Vault-Token", vaultToken); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<Map<String, Long>> request = new HttpEntity<Map<String,Long>>(requestBody, headers); return request; }
Example 13
Source File: GitlabDataGrabber.java From Refactoring-Bot with MIT License | 5 votes |
/** * This method tries to get a repository from GitLab. * * @param repoName * @param repoOwner * @param botToken * @param apiLink * @throws GitLabAPIException */ public GitLabRepository checkRepository(String repoName, String repoOwner, String botToken, String apiLink) throws GitLabAPIException { // Build URI URI gitlabURI = null; if (apiLink == null || apiLink.isEmpty()) { gitlabURI = URI.create(GITLAB_DEFAULT_APILINK + "/projects/" + repoOwner + "%2F" + repoName); } else { gitlabURI = URI.create(apiLink + "/projects/" + repoOwner + "%2F" + repoName); } RestTemplate rest = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.set("User-Agent", USER_AGENT); headers.set(TOKEN_HEADER, botToken); HttpEntity<String> entity = new HttpEntity<>("parameters", headers); try { // Send request to the GitLab-API return rest.exchange(gitlabURI, HttpMethod.GET, entity, GitLabRepository.class).getBody(); } catch (RestClientException e) { logger.error(e.getMessage(), e); throw new GitLabAPIException("Repository does not exist on GitLab or invalid Bot-Token!", e); } }
Example 14
Source File: FlowableIdmApplicationSecurityTest.java From flowable-engine with Apache License 2.0 | 5 votes |
@Test public void restUserWithCookieShouldNotBeAbleToAccessApi() { HttpHeaders headers = new HttpHeaders(); headers.set(HttpHeaders.COOKIE, rememberMeCookie("rest", "test-rest-value")); HttpEntity<?> request = new HttpEntity<>(headers); String processDefinitionsUrl = "http://localhost:" + serverPort + "/flowable-idm/api/idm/users"; ResponseEntity<Object> result = restTemplate.exchange(processDefinitionsUrl, HttpMethod.GET, request, Object.class); assertThat(result.getStatusCode()) .as("GET IDM Api Users") .isEqualTo(HttpStatus.UNAUTHORIZED); }
Example 15
Source File: PortfolioController.java From cf-SpringBootTrader with Apache License 2.0 | 4 votes |
private HttpHeaders getNoCacheHeaders() { HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.set("Cache-Control", "no-cache"); return responseHeaders; }
Example 16
Source File: ServletAnnotationControllerTests.java From spring4-understanding with Apache License 2.0 | 4 votes |
@RequestMapping("/bar") public ResponseEntity<String> bar() { HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.set("MyResponseHeader", "MyValue"); return new ResponseEntity<String>(responseHeaders, HttpStatus.NOT_FOUND); }
Example 17
Source File: PortfolioController.java From pivotal-bank-demo with Apache License 2.0 | 4 votes |
private HttpHeaders getNoCacheHeaders() { HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.set("Cache-Control", "no-cache"); return responseHeaders; }
Example 18
Source File: CreditDecisionPoller.java From event-driven-spring-boot with Apache License 2.0 | 4 votes |
@Scheduled(fixedDelay = 15000) public void poll() { HttpHeaders requestHeaders = new HttpHeaders(); if (lastModified != null) { requestHeaders.set("If-Modified-Since", DateUtils.formatDate(lastModified)); } HttpEntity<?> requestEntity = new HttpEntity(requestHeaders); ResponseEntity<Feed> response = restTemplate.exchange(creditDecisionFeed, HttpMethod.GET, requestEntity, Feed.class); if (response.getStatusCode() != HttpStatus.NOT_MODIFIED) { Feed feed = response.getBody(); Date lastUpdateInFeed = null; for (Entry entry : feed.getEntries()) { String applicationNumber = entry.getSummary().getValue(); if ((lastModified == null) || (entry.getUpdated().after(lastModified))) { log.info(applicationNumber + " is new, updating the status"); CreditApplicationStatus applicationStatus = repository.findByApplicationNumber(applicationNumber); if (applicationStatus != null) { applicationStatus.setApproved(true); repository.save(applicationStatus); } if ((lastUpdateInFeed == null) || (entry.getUpdated().after(lastUpdateInFeed))) { lastUpdateInFeed = entry.getUpdated(); } } } if (response.getHeaders().getFirst("Last-Modified") != null) { lastModified = DateUtils.parseDate(response.getHeaders().getFirst("Last-Modified")); log.info("LastModified header {}", lastModified); } else { if (lastUpdateInFeed != null) { lastModified = lastUpdateInFeed; log.info("Last in feed {}", lastModified); } } } }
Example 19
Source File: PrintingResultHandlerTests.java From spring4-understanding with Apache License 2.0 | 4 votes |
@Test @SuppressWarnings("deprecation") public void printResponse() throws Exception { Cookie enigmaCookie = new Cookie("enigma", "42"); enigmaCookie.setComment("This is a comment"); enigmaCookie.setHttpOnly(true); enigmaCookie.setMaxAge(1234); enigmaCookie.setDomain(".example.com"); enigmaCookie.setPath("/crumbs"); enigmaCookie.setSecure(true); this.response.setStatus(400, "error"); this.response.addHeader("header", "headerValue"); this.response.setContentType("text/plain"); this.response.getWriter().print("content"); this.response.setForwardedUrl("redirectFoo"); this.response.sendRedirect("/redirectFoo"); this.response.addCookie(new Cookie("cookie", "cookieValue")); this.response.addCookie(enigmaCookie); this.handler.handle(this.mvcResult); HttpHeaders headers = new HttpHeaders(); headers.set("header", "headerValue"); headers.setContentType(MediaType.TEXT_PLAIN); headers.setLocation(new URI("/redirectFoo")); String heading = "MockHttpServletResponse"; assertValue(heading, "Status", this.response.getStatus()); assertValue(heading, "Error message", response.getErrorMessage()); assertValue(heading, "Headers", headers); assertValue(heading, "Content type", this.response.getContentType()); assertValue(heading, "Body", this.response.getContentAsString()); assertValue(heading, "Forwarded URL", this.response.getForwardedUrl()); assertValue(heading, "Redirected URL", this.response.getRedirectedUrl()); Map<String, Map<String, Object>> printedValues = this.handler.getPrinter().printedValues; String[] cookies = (String[]) printedValues.get(heading).get("Cookies"); assertEquals(2, cookies.length); String cookie1 = cookies[0]; String cookie2 = cookies[1]; assertTrue(cookie1.startsWith("[" + Cookie.class.getSimpleName())); assertTrue(cookie1.contains("name = 'cookie', value = 'cookieValue'")); assertTrue(cookie1.endsWith("]")); assertTrue(cookie2.startsWith("[" + Cookie.class.getSimpleName())); assertTrue(cookie2.contains("name = 'enigma', value = '42', comment = 'This is a comment', domain = '.example.com', maxAge = 1234, path = '/crumbs', secure = true, version = 0, httpOnly = true")); assertTrue(cookie2.endsWith("]")); }
Example 20
Source File: GitHub.java From spring-data-dev-tools with Apache License 2.0 | 3 votes |
private HttpHeaders newUserScopedHttpHeaders() { HttpHeaders headers = new HttpHeaders(); headers.set("Authorization", properties.getHttpCredentials().toString()); return headers; }