当前位置: 首页>>代码示例>>Java>>正文


Java HttpHeaders类代码示例

本文整理汇总了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())));
}
 
开发者ID:xm-online,项目名称:xm-ms-dashboard,代码行数:19,代码来源:MicroserviceSecurityConfiguration.java

示例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);
}
 
开发者ID:CMSgov,项目名称:qpp-conversion-tool,代码行数:25,代码来源:CpcFileControllerV1.java

示例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);	
}
 
开发者ID:EsupPortail,项目名称:esup-sgc,代码行数:22,代码来源:WsRestEsupNfcController.java

示例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);
}
 
开发者ID:EsupPortail,项目名称:esup-sgc,代码行数:32,代码来源:WsRestEsupNfcController.java

示例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);
}
 
开发者ID:quanticc,项目名称:sentry,代码行数:20,代码来源:UserResource.java

示例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);
    }
}
 
开发者ID:tyro,项目名称:pact-spring-mvc,代码行数:25,代码来源:ReturnExpect.java

示例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;
}
 
开发者ID:zafar142007,项目名称:FolderSync,代码行数:21,代码来源:Auth.java

示例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;
            });
}
 
开发者ID:SopraSteriaGroup,项目名称:initiatives_backend_auth,代码行数:26,代码来源:TokenService.java

示例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);
}
 
开发者ID:jopache,项目名称:Settings,代码行数:29,代码来源:AuthorizationApi.java

示例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);
}
 
开发者ID:DRIVER-EU,项目名称:CommonInformationSpace,代码行数:25,代码来源:CISAdaptorConnectorRestController.java

示例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;
}
 
开发者ID:mrluo735,项目名称:cas-5.1.0,代码行数:19,代码来源:RestPasswordManagementService.java

示例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;
    }
 
开发者ID:deepu105,项目名称:spring-io,代码行数:23,代码来源:PaginationUtil.java

示例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);
}
 
开发者ID:osswangxining,项目名称:iotplatform,代码行数:22,代码来源:AuthController.java

示例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);
}
 
开发者ID:tdd-pingis,项目名称:tdd-pingpong,代码行数:22,代码来源:FakeSandboxRestService.java

示例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));
}
 
开发者ID:hantsy,项目名称:spring-microservice-sample,代码行数:22,代码来源:ControllerTest.java


注:本文中的org.springframework.http.HttpHeaders类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。