本文整理匯總了Java中org.springframework.http.HttpHeaders類的典型用法代碼示例。如果您正苦於以下問題:Java HttpHeaders類的具體用法?Java HttpHeaders怎麽用?Java HttpHeaders使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
HttpHeaders類屬於org.springframework.http包,在下文中一共展示了HttpHeaders類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: getKeyFromConfigServer
import org.springframework.http.HttpHeaders; //導入依賴的package包/類
private String getKeyFromConfigServer(RestTemplate keyUriRestTemplate) throws CertificateException {
// Load available UAA servers
discoveryClient.getServices();
HttpEntity<Void> request = new HttpEntity<Void>(new HttpHeaders());
String content = keyUriRestTemplate
.exchange("http://config/api/token_key", HttpMethod.GET, request, String.class).getBody();
if (StringUtils.isBlank(content)) {
throw new CertificateException("Received empty certificate from config.");
}
InputStream fin = new ByteArrayInputStream(content.getBytes());
CertificateFactory f = CertificateFactory.getInstance(Constants.CERTIFICATE);
X509Certificate certificate = (X509Certificate)f.generateCertificate(fin);
PublicKey pk = certificate.getPublicKey();
return String.format(Constants.PUBLIC_KEY, new String(Base64.encode(pk.getEncoded())));
}
示例2: getUnprocessedCpcPlusFiles
import org.springframework.http.HttpHeaders; //導入依賴的package包/類
/**
* Endpoint to transform an uploaded file into a valid or error json response
*
* @return Valid json or error json content
*/
@GetMapping(value = "/unprocessed-files",
headers = {"Accept=" + Constants.V1_API_ACCEPT})
public ResponseEntity<List<UnprocessedCpcFileData>> getUnprocessedCpcPlusFiles() {
API_LOG.info("CPC+ unprocessed files request received");
if (blockCpcPlusApi()) {
API_LOG.info(BLOCKED_BY_FEATURE_FLAG);
return new ResponseEntity<>(null, null, HttpStatus.FORBIDDEN);
}
List<UnprocessedCpcFileData> unprocessedCpcFileDataList = cpcFileService.getUnprocessedCpcPlusFiles();
API_LOG.info("CPC+ unprocessed files request succeeded");
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
return new ResponseEntity<>(unprocessedCpcFileDataList, httpHeaders, HttpStatus.OK);
}
示例3: getCnousCardId
import org.springframework.http.HttpHeaders; //導入依賴的package包/類
/**
* Exemple :
* curl -v -X GET -H "Content-Type: application/json" 'http://localhost:8080/wsrest/nfc/cnousCardId?authToken=123456&csn=123456789abcde'
*/
@RequestMapping(value = "/cnousCardId", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
@ResponseBody
public ResponseEntity<Long> getCnousCardId(@RequestParam String authToken, @RequestParam String csn) {
log.debug("getCnousCardId with csn = " + csn);
HttpHeaders responseHeaders = new HttpHeaders();
String eppnInit = clientJWSController.getEppnInit(authToken);
if(eppnInit == null) {
log.info("Bad authotoken : " + authToken);
return new ResponseEntity<Long>(new Long(-1), responseHeaders, HttpStatus.FORBIDDEN);
}
Card card = Card.findCardsByCsn(csn).getSingleResult();
String cnousCardId = cardIdsService.generateCardId(card.getId(), "crous");
log.debug("cnousCardId for csn " + csn + " = " + cnousCardId);
return new ResponseEntity<Long>(Long.valueOf(cnousCardId), responseHeaders, HttpStatus.OK);
}
示例4: addCrousCsvFile
import org.springframework.http.HttpHeaders; //導入依賴的package包/類
/**
* Exemple :
* curl --form "[email protected]/tmp/le-csv.txt" http://localhost:8080/wsrest/nfc/addCrousCsvFile?authToken=123456
* @throws IOException
* @throws ParseException
*/
@RequestMapping(value = "/addCrousCsvFile", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@ResponseBody
public ResponseEntity<String> addCrousCsvFile(@RequestParam String authToken, @RequestParam MultipartFile file, @RequestParam String csn) throws IOException, ParseException {
HttpHeaders responseHeaders = new HttpHeaders();
String eppnInit = clientJWSController.getEppnInit(authToken);
if(eppnInit == null) {
log.info("Bad authotoken : " + authToken);
return new ResponseEntity<String>("bad authotoken", responseHeaders, HttpStatus.FORBIDDEN);
}
// sometimes file is null here, but I don't know how to reproduce this issue ... maybe that can occur only with some specifics browsers ?
if(file != null) {
String filename = file.getOriginalFilename();
log.info("CrousSmartCardController retrieving file from rest call " + filename);
InputStream stream = new ByteArrayInputStream(file.getBytes());
Card card = Card.findCard(csn);
crousSmartCardService.consumeCsv(stream, false);
cardEtatService.setCardEtat(card, Etat.ENCODED, null, null, false, true);
if(appliConfigService.getEnableAuto()) {
cardEtatService.setCardEtatAsync(card.getId(), Etat.ENABLED, null, null, false, false);
}
return new ResponseEntity<String>("OK", responseHeaders, HttpStatus.OK);
}
return new ResponseEntity<String>("KO", responseHeaders, HttpStatus.BAD_REQUEST);
}
示例5: getAllUsers
import org.springframework.http.HttpHeaders; //導入依賴的package包/類
/**
* GET /users : get all users.
*
* @param pageable the pagination information
* @return the ResponseEntity with status 200 (OK) and with body all users
* @throws URISyntaxException if the pagination headers couldn't be generated
*/
@GetMapping("/users")
@Timed
@Secured(AuthoritiesConstants.ADMIN)
public ResponseEntity<List<ManagedUserVM>> getAllUsers(@ApiParam Pageable pageable)
throws URISyntaxException {
Page<User> page = userRepository.findAll(pageable);
List<ManagedUserVM> managedUserVMs = page.getContent().stream()
.map(ManagedUserVM::new)
.collect(Collectors.toList());
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/users");
return new ResponseEntity<>(managedUserVMs, headers, HttpStatus.OK);
}
示例6: assertRequestHeaders
import org.springframework.http.HttpHeaders; //導入依賴的package包/類
private void assertRequestHeaders(HttpHeaders actualHeaders, Object requestObject, Map<String, Matcher<? super List<String>>> additionalExpectedHeaders) {
Map<String, Matcher<? super List<String>>> expectedHeaders = new HashMap<>();
if (requestObject != null && requestObject instanceof HttpEntity) {
HttpEntity httpEntity = (HttpEntity) requestObject;
HttpHeaders headers = httpEntity.getHeaders();
Map<String, Matcher<List<String>>> stringMatcherMap = Maps.transformValues(headers, new Function<List<String>, Matcher<List<String>>>() {
@Override
public Matcher<List<String>> apply(List<String> input) {
return is(input);
}
});
expectedHeaders.putAll(stringMatcherMap);
}
expectedHeaders.putAll(additionalExpectedHeaders);
Set<String> headerNames = expectedHeaders.keySet();
for (String headerName : headerNames) {
Matcher<? super List<String>> headerValuesMatcher = expectedHeaders.get(headerName);
assertThat(format("Contains header %s", headerName), actualHeaders.containsKey(headerName), is(true));
assertThat(format("'%s' header value fails assertion", headerName), actualHeaders.get(headerName), headerValuesMatcher);
}
}
示例7: createNewUser
import org.springframework.http.HttpHeaders; //導入依賴的package包/類
@Override
public boolean createNewUser(String u, String p) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
ObjectMapper mapper=ObjectMapperPool.getMapper();
String json="";
try {
json = mapper.writeValueAsString(new LoginRequest(u, p, fingerPrint.getFingerPrint()));
HttpEntity<String> entity = new HttpEntity<String>(json, headers);
ResponseEntity<String> response=restTemplate.postForEntity(serverPath.concat(Constants.CREATE_USER_SUFFIX), entity, String.class);
CreateUserResponse resp=mapper.readValue(response.getBody(), CreateUserResponse.class);
logger.debug("Got create user response {}",resp.getStatus());
return resp.isResult();
} catch (Exception e) {
logger.error("Parse exception", e);
}
return false;
}
示例8: callSSOProvider
import org.springframework.http.HttpHeaders; //導入依賴的package包/類
public Mono<User> callSSOProvider(String accessToken, SSOProvider ssoProvider) {
SSOProperties.SSOValues keys = ssoProperties.getProviders().get(ssoProvider);
return WebClient.builder()
.build()
.get()
.uri(keys.getProfileUrl())
.header(HttpHeaders.AUTHORIZATION, OAuth2AccessToken.BEARER_TYPE + " " + accessToken)
.exchange()
.flatMap(resp -> resp.bodyToMono(Map.class))
.flatMap(body -> {
if(Integer.valueOf(401).equals(body.get("status"))){
return Mono.error(new ResponseStatusException(HttpStatus.UNAUTHORIZED, body.get("message").toString()));
} else {
return Mono.just(body);
}
})
.map(values -> new TokenService.UserSSO(values, keys))
.map(userSSO -> {
User user = new User();
user.setIdSSO(ssoProvider.toString() + "#" + userSSO.id);
user.setFirstName(userSSO.firstName);
user.setLastName(userSSO.lastName);
return user;
});
}
示例9: apiAuthorizationLoginPost
import org.springframework.http.HttpHeaders; //導入依賴的package包/類
/**
*
*
* <p><b>200</b> - Success
* @param model The model parameter
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public void apiAuthorizationLoginPost(LoginModel model) throws RestClientException {
Object postBody = model;
String path = UriComponentsBuilder.fromPath("/api/authorization/login").build().toUriString();
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
final String[] accepts = { };
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json-patch+json", "application/json", "text/json", "application/_*+json"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {};
apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
示例10: getOrganisationByName
import org.springframework.http.HttpHeaders; //導入依賴的package包/類
@ApiOperation(value = "getOrganisationByName", nickname = "getOrganisationByName")
@RequestMapping(value = "/CISConnector/getOrganisationByName/{organisation}", method = RequestMethod.GET)
@ApiImplicitParams({
@ApiImplicitParam(name = "organisation", value = "the Organisation name", required = true, dataType = "String", paramType = "path")
})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Success", response = ResponseEntity.class),
@ApiResponse(code = 400, message = "Bad Request", response = ResponseEntity.class),
@ApiResponse(code = 500, message = "Failure", response = ResponseEntity.class)})
public ResponseEntity<Organisation> getOrganisationByName(@PathVariable String organisation) throws CISCommunicationException {
log.info("--> getOrganisationByName: " + organisation);
Organisation organisationRes = null;
try {
organisationRes = connector.getOrganisationByName(organisation);
} catch (CISCommunicationException e) {
log.error("Error executing the request: Communication Error" , e);
organisationRes = null;
}
HttpHeaders responseHeaders = new HttpHeaders();
log.info("getOrganisationByName -->");
return new ResponseEntity<Organisation>(organisationRes, responseHeaders, HttpStatus.OK);
}
示例11: getSecurityQuestions
import org.springframework.http.HttpHeaders; //導入依賴的package包/類
@Override
public Map<String, String> getSecurityQuestions(final String username) {
final PasswordManagementProperties.Rest rest = passwordManagementProperties.getRest();
if (StringUtils.isBlank(rest.getEndpointUrlSecurityQuestions())) {
return null;
}
final HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.put("username", Arrays.asList(username));
final HttpEntity<String> entity = new HttpEntity<>(headers);
final ResponseEntity<Map> result = restTemplate.exchange(rest.getEndpointUrlSecurityQuestions(),
HttpMethod.GET, entity, Map.class);
if (result.getStatusCodeValue() == HttpStatus.OK.value() && result.hasBody()) {
return result.getBody();
}
return null;
}
示例12: generatePaginationHttpHeaders
import org.springframework.http.HttpHeaders; //導入依賴的package包/類
public static HttpHeaders generatePaginationHttpHeaders(Page page, String baseUrl) {
HttpHeaders headers = new HttpHeaders();
headers.add("X-Total-Count", Long.toString(page.getTotalElements()));
String link = "";
if ((page.getNumber() + 1) < page.getTotalPages()) {
link = "<" + generateUri(baseUrl, page.getNumber() + 1, page.getSize()) + ">; rel=\"next\",";
}
// prev link
if ((page.getNumber()) > 0) {
link += "<" + generateUri(baseUrl, page.getNumber() - 1, page.getSize()) + ">; rel=\"prev\",";
}
// last and first link
int lastPage = 0;
if (page.getTotalPages() > 0) {
lastPage = page.getTotalPages() - 1;
}
link += "<" + generateUri(baseUrl, lastPage, page.getSize()) + ">; rel=\"last\",";
link += "<" + generateUri(baseUrl, 0, page.getSize()) + ">; rel=\"first\"";
headers.add(HttpHeaders.LINK, link);
return headers;
}
示例13: checkActivateToken
import org.springframework.http.HttpHeaders; //導入依賴的package包/類
@RequestMapping(value = "/noauth/activate", params = { "activateToken" }, method = RequestMethod.GET)
public ResponseEntity<String> checkActivateToken(
@RequestParam(value = "activateToken") String activateToken) {
HttpHeaders headers = new HttpHeaders();
HttpStatus responseStatus;
UserCredentials userCredentials = userService.findUserCredentialsByActivateToken(activateToken);
if (userCredentials != null) {
String createPasswordURI = "/login/createPassword";
try {
URI location = new URI(createPasswordURI + "?activateToken=" + activateToken);
headers.setLocation(location);
responseStatus = HttpStatus.SEE_OTHER;
} catch (URISyntaxException e) {
log.error("Unable to create URI with address [{}]", createPasswordURI);
responseStatus = HttpStatus.BAD_REQUEST;
}
} else {
responseStatus = HttpStatus.CONFLICT;
}
return new ResponseEntity<>(headers, responseStatus);
}
示例14: buildResponseEntity
import org.springframework.http.HttpHeaders; //導入依賴的package包/類
private HttpEntity<MultiValueMap<String, String>> buildResponseEntity(
Submission submission, HttpHeaders headers) {
logger.debug("Building response entity");
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
try {
map.add("test_output", new ObjectMapper().writeValueAsString(
submission.getTestOutput()));
} catch (JsonProcessingException ex) {
logger.debug("POJO deserialization failed");
}
map.add("stdout", submission.getStdout());
map.add("stderr", submission.getStderr());
map.add("validations", submission.getValidations());
map.add("vm_log", submission.getVmLog());
map.add("token", submission.getId().toString());
map.add("status", submission.getStatus().toString());
map.add("exit_code", submission.getExitCode().toString());
return new HttpEntity<>(map, headers);
}
示例15: createPostWithMockUser
import org.springframework.http.HttpHeaders; //導入依賴的package包/類
@Test
@WithMockUser
public void createPostWithMockUser() throws Exception {
Post _data = Post.builder().title("my first post").content("my content of my post").build();
given(this.postService.createPost(any(PostForm.class)))
.willReturn(_data);
MvcResult result = this.mockMvc
.perform(
post("/posts")
.content(objectMapper.writeValueAsString(PostForm.builder().title("my first post").content("my content of my post").build()))
.contentType(MediaType.APPLICATION_JSON)
)
.andExpect(status().isCreated())
.andExpect(header().string(HttpHeaders.LOCATION, containsString("/posts")))
.andReturn();
log.debug("mvc result::" + result.getResponse().getContentAsString());
verify(this.postService, times(1)).createPost(any(PostForm.class));
}