Java Code Examples for org.springframework.http.HttpHeaders#add()

The following examples show how to use org.springframework.http.HttpHeaders#add() . 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:    From java-technology-stack with MIT License 6 votes vote down vote up
@Test  // SPR-15066
public void requestInterceptorCanAddExistingHeaderValueWithoutBody() throws Exception {
	ClientHttpRequestInterceptor interceptor = (request, body, execution) -> {
		request.getHeaders().add("MyHeader", "MyInterceptorValue");
		return execution.execute(request, body);

	HttpHeaders requestHeaders = new HttpHeaders();
	mockSentRequest(POST, "", requestHeaders);

	HttpHeaders entityHeaders = new HttpHeaders();
	entityHeaders.add("MyHeader", "MyEntityValue");
	HttpEntity<Void> entity = new HttpEntity<>(null, entityHeaders);"", POST, entity, Void.class);
	assertThat(requestHeaders.get("MyHeader"), contains("MyEntityValue", "MyInterceptorValue"));

Example 2
Source File:    From micro-ecommerce with Apache License 2.0 6 votes vote down vote up
@HystrixCommand(fallbackMethod = "stubReviews")
public Observable<Collection<Review>> reviewsFor(final String productId, final String token) {

	// For some reason token overlay doesn't work. so the workaround ...
	HttpHeaders headers = new HttpHeaders();
	headers.add("Authorization", token);
	HttpEntity<String> request = new HttpEntity<String>(headers);

	return Observable.create(new Observable.OnSubscribe<Collection<Review>>() {
		public void call(Subscriber<? super Collection<Review>> observer) {
			try {
				if (!observer.isUnsubscribed()) {
									HttpMethod.GET, request, ReviewsResource.class, productId)
			} catch (Exception e) {
Example 3
Source File:    From tutorials with MIT License 6 votes vote down vote up
public void testRedisControlsSession() {
    ResponseEntity<String> result = testRestTemplateWithAuth.getForEntity(getTestUrl(), String.class);
    assertEquals("hello admin", result.getBody()); // login worked

    Set<String> redisResult = jedis.keys("*");
    assertTrue(redisResult.size() > 0); // redis is populated with session data

    String sessionCookie = result.getHeaders().get("Set-Cookie").get(0).split(";")[0];
    HttpHeaders headers = new HttpHeaders();
    headers.add("Cookie", sessionCookie);
    HttpEntity<String> httpEntity = new HttpEntity<>(headers);

    result =, HttpMethod.GET, httpEntity, String.class);
    assertEquals("hello admin", result.getBody()); // access with session works worked

    jedis.flushAll(); // clear all keys in redis

    result =, HttpMethod.GET, httpEntity, String.class);
    assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode());// access denied after sessions are removed in redis
Example 4
Source File:    From cloud-security-xsuaa-integration with Apache License 2.0 6 votes vote down vote up
public void retrieveToken() throws OAuth2ServiceException {
	TokenServiceHttpEntityMatcher tokenHttpEntityMatcher = new TokenServiceHttpEntityMatcher();
	tokenHttpEntityMatcher.addParameter(OAuth2TokenServiceConstants.PARAMETER_CLIENT_ID, clientCredentials.getId());

	HttpHeaders expectedHeaders = new HttpHeaders();
	expectedHeaders.add(HttpHeaders.ACCEPT, "application/json");
	expectedHeaders.add(HttpHeaders.AUTHORIZATION, "Bearer " + userTokenToBeExchanged);
	HttpEntity expectedRequest = new HttpEntity(expectedHeaders);

			.thenReturn(new ResponseEntity<>(responseMap, HttpStatus.OK));

	OAuth2TokenResponse accessToken = cut.retrieveAccessTokenViaUserTokenGrant(tokenEndpoint, clientCredentials,
			userTokenToBeExchanged, null, null);
	assertThat(accessToken.getRefreshToken(), is(responseMap.get(REFRESH_TOKEN)));
	assertThat(accessToken.getAccessToken(), is(responseMap.get(ACCESS_TOKEN)));
Example 5
Source File:    From spring-cloud-netflix with Apache License 2.0 5 votes vote down vote up
public EurekaHttpResponse<Void> register(InstanceInfo info) {
	String urlPath = serviceUrl + "apps/" + info.getAppName();

	HttpHeaders headers = new HttpHeaders();
	headers.add(HttpHeaders.ACCEPT_ENCODING, "gzip");
	headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);

	ResponseEntity<Void> response =, HttpMethod.POST,
			new HttpEntity<>(info, headers), Void.class);

	return anEurekaHttpResponse(response.getStatusCodeValue())
Example 6
Source File:    From java-technology-stack with MIT License 5 votes vote down vote up
@Test // SPR-17525
public void shouldNotDoubleEncode() throws Exception {
	HttpHeaders headers = new HttpHeaders();
	headers.add("Forwarded", "host=;proto=https");

	ServerHttpRequest request = MockServerHttpRequest
			.method(HttpMethod.GET, new URI(""))

	request = this.requestMutator.apply(request);

	assertEquals(new URI(""), request.getURI());
Example 7
Source File:    From kaif with Apache License 2.0 5 votes vote down vote up
public ResponseEntity<V1ErrorResponse> handleInvalidTokenException(final InvalidTokenException ex,
    final WebRequest request) {
  final HttpStatus status = HttpStatus.UNAUTHORIZED;
  final V1ErrorResponse errorResponse = createErrorResponse(status, "invalid access token");
  HttpHeaders responseHeaders = new HttpHeaders();
  String error = pair(OauthErrors.OAUTH_ERROR, OauthErrors.ResourceResponse.INVALID_TOKEN);
  String errorDesc = pair(OauthErrors.OAUTH_ERROR_DESCRIPTION, "invalid token");
      asList(realm(), error, errorDesc).stream().collect(joining(", ")));
  return new ResponseEntity<>(errorResponse, responseHeaders, status);
Example 8
Source File:    From onboard with Apache License 2.0 5 votes vote down vote up
private HttpHeaders addAuthToHeader(HttpHeaders headers) {
    String authHeader = getAuthorizationValue();
    if (authHeader != null) {
        return headers;
    headers.add("Authorization", authHeader);
    return headers;
Example 9
Source File:    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
public void testNormal() {
  Holder<Invocation> holder = new Holder<>();
  CseClientHttpRequest client =
      new CseClientHttpRequest(
          URI.create("cse://defaultMicroservice/" + SpringmvcImpl.class.getSimpleName() + "/bytes"),
          HttpMethod.POST) {

         * {@inheritDoc}
        protected Response doInvoke(Invocation invocation) {
          holder.value = invocation;
          return Response.ok("result");
  byte[] body = "abc".getBytes();
  HttpHeaders headers = new HttpHeaders();
  headers.add("token", "123");


  Assert.assertArrayEquals(body, (byte[]) holder.value.getInvocationArguments().get("input"));
  Assert.assertEquals("123", holder.value.getInvocationArguments().get("token"));
Example 10
Source File:    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
private RestOperations mockRestOperations() throws Exception {
	Map<String, String> payload = new HashMap<>();
	payload.put("one", keyGeneratorUtils.getPublicKeyCertificate());
	HttpHeaders headers = new HttpHeaders();
	headers.add(HttpHeaders.CACHE_CONTROL, CacheControl.maxAge(3600L, TimeUnit.SECONDS).getHeaderValue());
	ResponseEntity<Map<String, String>> response = new ResponseEntity<>(payload, headers, HttpStatus.OK);
	return mockRestOperations(response);
Example 11
Source File:    From java-technology-stack with MIT License 5 votes vote down vote up
public HttpHeaders getResponseHeaders() {
	HttpHeaders headers = (this.original instanceof HttpResource ?
			((HttpResource) this.original).getResponseHeaders() : new HttpHeaders());
	headers.add(HttpHeaders.CONTENT_ENCODING, "gzip");
	headers.add(HttpHeaders.VARY, HttpHeaders.ACCEPT_ENCODING);
	return headers;
Example 12
Source File:    From singleton with Eclipse Public License 2.0 5 votes vote down vote up
public boolean sendToRemote(String url, Map<String, Object> requestParam) {"Send data to remote server [{}] ...", url);"The request body is: {}", requestParam);
	boolean result = false;
	RestTemplate restTemplate = new RestTemplate();
	HttpHeaders headers = new HttpHeaders();
	MediaType type = MediaType
			.parseMediaType("application/json; charset=UTF-8");
	headers.add("Accept", MediaType.APPLICATION_JSON.toString());
	JSONObject jsonObj = new JSONObject(requestParam);
	HttpEntity<String> formEntity = new HttpEntity<String>(
			jsonObj.toString(), headers);
	try {
		ResponseEntity<GRMResponseDTO> responseEntity = restTemplate
				.postForEntity(url, formEntity, GRMResponseDTO.class);
		GRMResponseDTO gRMResponseDTO = responseEntity.getBody();
		if (gRMResponseDTO.getStatus() == GRMAPIResponseStatus.CREATED
				.getCode()) {
			result = true;"The request has successed, the result: {} {}", gRMResponseDTO.getStatus(),  gRMResponseDTO.getResult());
		} else {"The request has failed, the response code: {} reason: {}", + gRMResponseDTO.getStatus(), gRMResponseDTO.getErrorMessage());
	} catch (Exception e) {
		result = false;
	return result;
Example 13
Source File:    From Cerberus with MIT License 5 votes vote down vote up
public static HttpEntity<Object> buildRequestEntityWithoutAuthenticationToken(Object body) {
  HttpHeaders headers = new HttpHeaders();
  headers.add("Content-Type", "application/json");
  HttpEntity<Object> entity = new HttpEntity<Object>(
  return entity;
Example 14
Source File:    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
private FraudServiceResponse sendRequestToFraudDetectionService(
		FraudServiceRequest request) {
	HttpHeaders httpHeaders = new HttpHeaders();

	ResponseEntity<FraudServiceResponse> response =
			"http://localhost:" + this.port + "/fraudcheck", HttpMethod.PUT,
			new HttpEntity<>(request, httpHeaders), FraudServiceResponse.class);

	return response.getBody();
Example 15
Source File:    From cubeai with Apache License 2.0 5 votes vote down vote up
public static HttpHeaders createFailureAlert(String entityName, String errorKey, String defaultMessage) {
    log.error("Entity processing failed, {}", defaultMessage);
    HttpHeaders headers = new HttpHeaders();
    headers.add("X-umdApp-error", defaultMessage);
    headers.add("X-umdApp-params", entityName);
    return headers;
Example 16
Source File:    From sakai with Educational Community License v2.0 5 votes vote down vote up
 * Returns the ToolItemRubricAssociation resource for the given tool and associated item ID, wrapped as an Optional.
 * @param toolId the tool id, something like "sakai.assignment"
 * @param associatedToolItemId the id of the associated element within the tool
 * @return
protected Optional<Resource<ToolItemRubricAssociation>> getRubricAssociationResource(String toolId, String associatedToolItemId, String siteId) throws Exception {

    TypeReferences.ResourcesType<Resource<ToolItemRubricAssociation>> resourceParameterizedTypeReference =
            new TypeReferences.ResourcesType<Resource<ToolItemRubricAssociation>>() {};

    URI apiBaseUrl = new URI(serverConfigurationService.getServerUrl() + RBCS_SERVICE_URL_PREFIX);
    Traverson traverson = new Traverson(apiBaseUrl, MediaTypes.HAL_JSON);

    Traverson.TraversalBuilder builder = traverson.follow("rubric-associations", "search",

    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", String.format("Bearer %s", generateJsonWebToken(toolId, siteId)));

    Map<String, Object> parameters = new HashMap<>();
    parameters.put("toolId", toolId);
    parameters.put("itemId", associatedToolItemId);

    Resources<Resource<ToolItemRubricAssociation>> associationResources = builder.withTemplateParameters(

    // Should only be one matching this search criterion
    if (associationResources.getContent().size() > 1) {
        throw new IllegalStateException(String.format(
                "Number of rubric association resources greater than one for request: %s",

    Optional<Resource<ToolItemRubricAssociation>> associationResource = associationResources.getContent().stream().findFirst();

    return associationResource;
Example 17
Source File:    From openapi-generator with Apache License 2.0 5 votes vote down vote up
 * Deletes a pet
 * <p><b>200</b> - successful operation
 * <p><b>400</b> - Invalid pet value
 * @param petId Pet id to delete
 * @param apiKey The apiKey parameter
 * @throws WebClientResponseException if an error occurs while attempting to invoke the API
public Mono<Void> deletePet(Long petId, String apiKey) throws WebClientResponseException {
    Object postBody = null;
    // verify the required parameter 'petId' is set
    if (petId == null) {
        throw new WebClientResponseException("Missing the required parameter 'petId' when calling deletePet", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null);
    // create path and map variables
    final Map<String, Object> pathParams = new HashMap<String, Object>();

    pathParams.put("petId", petId);

    final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
    final HttpHeaders headerParams = new HttpHeaders();
    final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>();
    final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();

    if (apiKey != null)
    headerParams.add("api_key", apiClient.parameterToString(apiKey));
    final String[] localVarAccepts = { };
    final List<MediaType> localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
    final String[] localVarContentTypes = { };
    final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);

    String[] localVarAuthNames = new String[] { "petstore_auth" };

    ParameterizedTypeReference<Void> localVarReturnType = new ParameterizedTypeReference<Void>() {};
    return apiClient.invokeAPI("/pet/{petId}", HttpMethod.DELETE, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
Example 18
Source File:    From java-technology-stack with MIT License 5 votes vote down vote up
@Test  // SPR-16318
public void exceptionFromMethodWithProducesCondition() throws Exception {
	try {
		HttpHeaders headers = new HttpHeaders();
		headers.add("Accept", "text/csv, application/problem+json");
		performGet("/SPR-16318", headers, String.class).getBody();
	catch (HttpStatusCodeException ex) {
		assertEquals(500, ex.getRawStatusCode());
		assertEquals("application/problem+json;charset=UTF-8", ex.getResponseHeaders().getContentType().toString());
		assertEquals("{\"reason\":\"error\"}", ex.getResponseBodyAsString());
Example 19
Source File:    From jhipster-ribbon-hystrix with GNU General Public License v3.0 4 votes vote down vote up
public static HttpHeaders createAlert(String message, String param) {
    HttpHeaders headers = new HttpHeaders();
    headers.add("X-<%=angularAppName%>-alert", message);
    headers.add("X-<%=angularAppName%>-params", param);
    return headers;
Example 20
Source File:    From SDA with BSD 2-Clause "Simplified" License 4 votes vote down vote up
 * resourceinfo용 API
 * @param cmid
 * @param args
 * @return ResponseEntity<Object>
@RequestMapping(value = "/resourceinfo/{cmid}", method = RequestMethod.GET)
public @ResponseBody ResponseEntity<Object> getResourceInfo(@PathVariable String cmid, @RequestParam(value="p")  String args){
	ResponseEntity<Object> entity = null;
	HttpHeaders responseHeaders = new HttpHeaders();"/resourceinfo/{cmid} GET getResourceInfo start================>");

	List<Map<String, String>> returnMsg = new ArrayList<Map<String, String>>();
	ResponseMessageOk ok = new ResponseMessageOk();
	ok.setTime(Utils.dateFormat.format(new Date()));
	try {
		if(args.equals("")) {
			throw new UserDefinedException(HttpStatus.BAD_REQUEST, "Not Valid Argument.");

		String rtnStr = Utils.getDeviceInfo("<"+args+">");
		if( ! rtnStr.contains("rdf:resource")) {
			entity = new ResponseEntity<Object>(ok, responseHeaders, HttpStatus.NOT_FOUND);
		} else {
			entity = new ResponseEntity<Object>(ok, responseHeaders, HttpStatus.OK);

		Map<String, String > msgMap = new HashMap<String, String>();
		rtnStr = replaceBlankNodeId(rtnStr);
		msgMap.put("resource_information", rtnStr);
	} catch (Exception e) {
		ResponseMessage resultMsg = Utils.makeResponseBody(e);
		log.debug("ExceptionCause : "+resultMsg.getMessage());

		responseHeaders.add("ExceptionCause", resultMsg.getMessage());
		responseHeaders.add("ExceptionClass", e.getClass().getName());
		List<Map<String, String>> msg = new ArrayList<Map<String, String>>();
		HashMap<String, String> hm = new HashMap<String, String>();
		hm.put("err_msg", resultMsg.getMessage() );


		entity = new ResponseEntity<Object>(msg, responseHeaders,	HttpStatus.valueOf(resultMsg.getCode()));
	}"/resourceinfo/{cmid} GET getResourceInfo end================>");
	return entity;