List of usage examples for org.springframework.http HttpHeaders set
@Override public void set(String headerName, @Nullable String headerValue)
From source file:org.springframework.web.client.RestTemplateIntegrationTests.java
@Test public void exchangeGet() throws Exception { HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.set("MyHeader", "MyValue"); HttpEntity<?> requestEntity = new HttpEntity(requestHeaders); ResponseEntity<String> response = template.exchange(baseUrl + "/{method}", HttpMethod.GET, requestEntity, String.class, "get"); assertEquals("Invalid content", helloWorld, response.getBody()); }
From source file:org.springframework.web.client.RestTemplateIntegrationTests.java
@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());// w w w. j a va2s .co m }
From source file:org.stilavia.service.zalando.RequestContext.java
public <E> E execute(RestUriBuilder uriBuilder, ParameterizedTypeReference<E> entityClass) throws IOException, URISyntaxException { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); headers.set("Accept-Language", domain.getLocale()); headers.set("Accept-Encoding", "gzip,deflate"); if (this.clientId != null) { headers.set("x-client-name", this.clientId); }//w w w . j a v a2s . co m HttpEntity<E> httpEntity = new HttpEntity<E>(headers); ResponseEntity<E> response = restTemplate.exchange(uriBuilder.build(), HttpMethod.GET, httpEntity, entityClass); return response.getBody(); }
From source file:org.tnova.service.catalog.service.impl.SlaServiceImpl.java
private static HttpHeaders createHeaders(String username, String password) { HttpHeaders httpHeaders = new HttpHeaders(); // Create authentication string String auth = username + ":" + password; byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII"))); String authHeader = "Basic " + new String(encodedAuth); httpHeaders.set("Authorization", authHeader); httpHeaders.setContentType(MediaType.APPLICATION_JSON); List<MediaType> mediaTypes = new ArrayList<>(); mediaTypes.add(MediaType.APPLICATION_JSON); httpHeaders.setAccept(mediaTypes);/*from w w w . ja va 2 s . c om*/ return httpHeaders; }
From source file:org.zalando.riptide.ExecuteTest.java
@Test public void shouldSendHeaders() { server.expect(requestTo(url)).andExpect(header("X-Foo", "bar")).andRespond(withSuccess()); final HttpHeaders headers = new HttpHeaders(); headers.set("X-Foo", "bar"); unit.execute(GET, url, headers);/*w w w.jav a 2 s. co m*/ }
From source file:org.zalando.riptide.ExecuteTest.java
@Test public void shouldSendHeadersAndBody() { server.expect(requestTo(url)).andExpect(header("X-Foo", "bar")) .andExpect(content().string("{\"foo\":\"bar\"}")).andRespond(withSuccess()); final HttpHeaders headers = new HttpHeaders(); headers.set("X-Foo", "bar"); unit.execute(GET, url, headers, ImmutableMap.of("foo", "bar")); }
From source file:pl.edu.icm.cermine.web.controller.CermineController.java
@RequestMapping(value = "/download.html") public ResponseEntity<String> downloadXML(@RequestParam("task") long taskId, @RequestParam("type") String resultType, Model model) throws NoSuchTaskException { ExtractionTask task = taskManager.getTask(taskId); if ("nlm".equals(resultType)) { String nlm = task.getResult().getNlm(); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.set("Content-Type", "application/xml;charset=utf-8"); return new ResponseEntity<String>(nlm, responseHeaders, HttpStatus.OK); } else {//w w w .j a va 2 s . c o m throw new RuntimeException("Unknown request type: " + resultType); } }
From source file:sg.ncl.MainController.java
@RequestMapping(value = "/login", method = RequestMethod.POST) public String loginSubmit(@Valid @ModelAttribute("loginForm") LoginForm loginForm, BindingResult bindingResult, Model model, HttpSession session, final RedirectAttributes redirectAttributes) throws WebServiceRuntimeException { if (bindingResult.hasErrors()) { loginForm.setErrorMsg(ERR_INVALID_CREDENTIALS); return LOGIN_PAGE; }//from ww w . ja v a 2 s . c o m String inputEmail = loginForm.getLoginEmail(); String inputPwd = loginForm.getLoginPassword(); if (inputEmail.trim().isEmpty() || inputPwd.trim().isEmpty()) { loginForm.setErrorMsg("Email or Password cannot be empty!"); return LOGIN_PAGE; } String plainCreds = inputEmail + ":" + inputPwd; byte[] plainCredsBytes = plainCreds.getBytes(); byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes); String base64Creds = new String(base64CredsBytes); ResponseEntity response; HttpHeaders headers = new HttpHeaders(); headers.set(AUTHORIZATION, "Basic " + base64Creds); HttpEntity<String> request = new HttpEntity<>(headers); restTemplate.setErrorHandler(new MyResponseErrorHandler()); try { response = restTemplate.exchange(properties.getSioAuthUrl(), HttpMethod.POST, request, String.class); } catch (RestClientException e) { log.warn("Error connecting to sio authentication service: {}", e); loginForm.setErrorMsg(ERR_SERVER_OVERLOAD); return LOGIN_PAGE; } String jwtTokenString = response.getBody().toString(); // log.info("token string {}", jwtTokenString); if (jwtTokenString == null || jwtTokenString.isEmpty()) { log.warn("login failed for {}: unknown response code", loginForm.getLoginEmail()); loginForm.setErrorMsg(ERR_INVALID_CREDENTIALS); return LOGIN_PAGE; } if (RestUtil.isError(response.getStatusCode())) { try { MyErrorResource error = objectMapper.readValue(jwtTokenString, MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); if (exceptionState == ExceptionState.CREDENTIALS_NOT_FOUND_EXCEPTION) { log.warn("login failed for {}: credentials not found", loginForm.getLoginEmail()); loginForm.setErrorMsg("Login failed: Account does not exist. Please register."); return LOGIN_PAGE; } log.warn("login failed for {}: {}", loginForm.getLoginEmail(), error.getError()); loginForm.setErrorMsg(ERR_INVALID_CREDENTIALS); return LOGIN_PAGE; } catch (IOException ioe) { log.warn(LOG_IOEXCEPTION, ioe); throw new WebServiceRuntimeException(ioe.getMessage()); } } JSONObject tokenObject = new JSONObject(jwtTokenString); String token = tokenObject.getString("token"); String id = tokenObject.getString("id"); String role = ""; if (tokenObject.getJSONArray("roles") != null) { role = tokenObject.getJSONArray("roles").get(0).toString(); } if (token.trim().isEmpty() || id.trim().isEmpty() || role.trim().isEmpty()) { log.warn("login failed for {}: empty id {} or token {} or role {}", loginForm.getLoginEmail(), id, token, role); loginForm.setErrorMsg(ERR_INVALID_CREDENTIALS); return LOGIN_PAGE; } // now check user status to decide what to show to the user return checkUserStatus(loginForm, session, redirectAttributes, token, id, role); }
From source file:sg.ncl.MainController.java
/** * Creates a HttpEntity with a request body and header * * @param jsonString The JSON request converted to string * @return A HttpEntity request//from www .j a v a2s. co m * @implNote Authorization header must be set to the JwTToken in the format [Bearer: TOKEN_ID] * @see HttpEntity createHttpEntityHeaderOnly() for request with only header */ protected HttpEntity<String> createHttpEntityWithBody(String jsonString) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.set(AUTHORIZATION, httpScopedSession.getAttribute(webProperties.getSessionJwtToken()).toString()); return new HttpEntity<>(jsonString, headers); }
From source file:sg.ncl.MainController.java
/** * Creates a HttpEntity that contains only a header and empty body * * @return A HttpEntity request// ww w. j a v a 2 s.c o m * @implNote Authorization header must be set to the JwTToken in the format [Bearer: TOKEN_ID] * @see HttpEntity createHttpEntityWithBody() for request with both body and header */ protected HttpEntity<String> createHttpEntityHeaderOnly() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.set(AUTHORIZATION, httpScopedSession.getAttribute(webProperties.getSessionJwtToken()).toString()); return new HttpEntity<>(headers); }