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: RestTemplateTests.java From java-technology-stack with MIT License | 6 votes |
@Test // SPR-15066 public void requestInterceptorCanAddExistingHeaderValueWithoutBody() throws Exception { ClientHttpRequestInterceptor interceptor = (request, body, execution) -> { request.getHeaders().add("MyHeader", "MyInterceptorValue"); return execution.execute(request, body); }; template.setInterceptors(Collections.singletonList(interceptor)); HttpHeaders requestHeaders = new HttpHeaders(); mockSentRequest(POST, "http://example.com", requestHeaders); mockResponseStatus(HttpStatus.OK); HttpHeaders entityHeaders = new HttpHeaders(); entityHeaders.add("MyHeader", "MyEntityValue"); HttpEntity<Void> entity = new HttpEntity<>(null, entityHeaders); template.exchange("http://example.com", POST, entity, Void.class); assertThat(requestHeaders.get("MyHeader"), contains("MyEntityValue", "MyInterceptorValue")); verify(response).close(); }
Example 2
Source File: ReviewsIntegrationService.java From micro-ecommerce with Apache License 2.0 | 6 votes |
@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>>() { @Override public void call(Subscriber<? super Collection<Review>> observer) { try { if (!observer.isUnsubscribed()) { observer.onNext(restTemplate .exchange("http://reviews-service/reviews/search/findByProductId?productId={productId}", HttpMethod.GET, request, ReviewsResource.class, productId) .getBody().getContent()); observer.onCompleted(); } } catch (Exception e) { observer.onError(e); } } }); }
Example 3
Source File: SessionControllerIntegrationTest.java From tutorials with MIT License | 6 votes |
@Test 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 = testRestTemplate.exchange(getTestUrl(), HttpMethod.GET, httpEntity, String.class); assertEquals("hello admin", result.getBody()); // access with session works worked jedis.flushAll(); // clear all keys in redis result = testRestTemplate.exchange(getTestUrl(), HttpMethod.GET, httpEntity, String.class); assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode());// access denied after sessions are removed in redis }
Example 4
Source File: XsuaaOAuth2TokenServiceUserTokenTest.java From cloud-security-xsuaa-integration with Apache License 2.0 | 6 votes |
@Test public void retrieveToken() throws OAuth2ServiceException { TokenServiceHttpEntityMatcher tokenHttpEntityMatcher = new TokenServiceHttpEntityMatcher(); tokenHttpEntityMatcher.setGrantType(OAuth2TokenServiceConstants.GRANT_TYPE_USER_TOKEN); 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); Mockito.when(mockRestOperations .postForEntity( eq(tokenEndpoint), argThat(tokenHttpEntityMatcher), eq(Map.class))) .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))); assertNotNull(accessToken.getExpiredAtDate()); }
Example 5
Source File: RestTemplateEurekaHttpClient.java From spring-cloud-netflix with Apache License 2.0 | 5 votes |
@Override 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 = restTemplate.exchange(urlPath, HttpMethod.POST, new HttpEntity<>(info, headers), Void.class); return anEurekaHttpResponse(response.getStatusCodeValue()) .headers(headersOf(response)).build(); }
Example 6
Source File: ForwardedHeaderTransformerTests.java From java-technology-stack with MIT License | 5 votes |
@Test // SPR-17525 public void shouldNotDoubleEncode() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.add("Forwarded", "host=84.198.58.199;proto=https"); ServerHttpRequest request = MockServerHttpRequest .method(HttpMethod.GET, new URI("http://example.com/a%20b?q=a%2Bb")) .headers(headers) .build(); request = this.requestMutator.apply(request); assertEquals(new URI("https://84.198.58.199/a%20b?q=a%2Bb"), request.getURI()); assertForwardedHeadersRemoved(request); }
Example 7
Source File: V1ExceptionHandler.java From kaif with Apache License 2.0 | 5 votes |
@ExceptionHandler(InvalidTokenException.class) @ResponseBody 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"); responseHeaders.add(Oauths.HeaderType.WWW_AUTHENTICATE, asList(realm(), error, errorDesc).stream().collect(joining(", "))); return new ResponseEntity<>(errorResponse, responseHeaders, status); }
Example 8
Source File: NetServiceImpl.java From onboard with Apache License 2.0 | 5 votes |
private HttpHeaders addAuthToHeader(HttpHeaders headers) { String authHeader = getAuthorizationValue(); if (authHeader != null) { return headers; } headers.add("Authorization", authHeader); return headers; }
Example 9
Source File: TestCseClientHttpRequest.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
@Test public void testNormal() { Holder<Invocation> holder = new Holder<>(); CseClientHttpRequest client = new CseClientHttpRequest( URI.create("cse://defaultMicroservice/" + SpringmvcImpl.class.getSimpleName() + "/bytes"), HttpMethod.POST) { /** * {@inheritDoc} */ @Override protected Response doInvoke(Invocation invocation) { holder.value = invocation; return Response.ok("result"); } }; byte[] body = "abc".getBytes(); HttpHeaders headers = new HttpHeaders(); headers.add("token", "123"); client.setRequestBody(body); client.setHttpHeaders(headers); client.execute(); Assert.assertArrayEquals(body, (byte[]) holder.value.getInvocationArguments().get("input")); Assert.assertEquals("123", holder.value.getInvocationArguments().get("token")); }
Example 10
Source File: FirebaseJwtTokenDecoderTests.java From spring-cloud-gcp with Apache License 2.0 | 5 votes |
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: GzipResourceResolver.java From java-technology-stack with MIT License | 5 votes |
@Override 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: SourceDaoImpl.java From singleton with Eclipse Public License 2.0 | 5 votes |
@Override public boolean sendToRemote(String url, Map<String, Object> requestParam) { LOGGER.info("Send data to remote server [{}] ...", url); LOGGER.info("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.setContentType(type); 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; LOGGER.info("The request has successed, the result: {} {}", gRMResponseDTO.getStatus(), gRMResponseDTO.getResult()); } else { LOGGER.info("The request has failed, the response code: {} reason: {}", + gRMResponseDTO.getStatus(), gRMResponseDTO.getErrorMessage()); } } catch (Exception e) { result = false; } return result; }
Example 13
Source File: RequestEntityBuilder.java From Cerberus with MIT License | 5 votes |
public static HttpEntity<Object> buildRequestEntityWithoutAuthenticationToken(Object body) { HttpHeaders headers = new HttpHeaders(); headers.add("Content-Type", "application/json"); HttpEntity<Object> entity = new HttpEntity<Object>( body, headers ); return entity; }
Example 14
Source File: LoanApplicationService.java From spring-cloud-contract with Apache License 2.0 | 5 votes |
private FraudServiceResponse sendRequestToFraudDetectionService( FraudServiceRequest request) { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add(HttpHeaders.CONTENT_TYPE, FRAUD_SERVICE_JSON_VERSION_1); ResponseEntity<FraudServiceResponse> response = this.restTemplate.exchange( "http://localhost:" + this.port + "/fraudcheck", HttpMethod.PUT, new HttpEntity<>(request, httpHeaders), FraudServiceResponse.class); return response.getBody(); }
Example 15
Source File: HeaderUtil.java From cubeai with Apache License 2.0 | 5 votes |
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: RubricsServiceImpl.java From sakai with Educational Community License v2.0 | 5 votes |
/** * 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", "by-tool-item-ids"); HttpHeaders headers = new HttpHeaders(); headers.add("Authorization", String.format("Bearer %s", generateJsonWebToken(toolId, siteId))); builder.withHeaders(headers); Map<String, Object> parameters = new HashMap<>(); parameters.put("toolId", toolId); parameters.put("itemId", associatedToolItemId); Resources<Resource<ToolItemRubricAssociation>> associationResources = builder.withTemplateParameters( parameters).toObject(resourceParameterizedTypeReference); // 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", associationResources.getLink(Link.REL_SELF).toString())); } Optional<Resource<ToolItemRubricAssociation>> associationResource = associationResources.getContent().stream().findFirst(); return associationResource; }
Example 17
Source File: PetApi.java From openapi-generator with Apache License 2.0 | 5 votes |
/** * 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: RequestMappingExceptionHandlingIntegrationTests.java From java-technology-stack with MIT License | 5 votes |
@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(); fail(); } 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: _HeaderUtil.java From jhipster-ribbon-hystrix with GNU General Public License v3.0 | 4 votes |
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: SfController.java From SDA with BSD 2-Clause "Simplified" License | 4 votes |
/** * 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(); log.info("/resourceinfo/{cmid} GET getResourceInfo start================>"); List<Map<String, String>> returnMsg = new ArrayList<Map<String, String>>(); ResponseMessageOk ok = new ResponseMessageOk(); ok.setCmd(Utils.CMD); ok.setContextId(cmid); 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); returnMsg.add(msgMap); ok.setContents(returnMsg); } 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() ); ok.setContents(msg); entity = new ResponseEntity<Object>(msg, responseHeaders, HttpStatus.valueOf(resultMsg.getCode())); } log.info("/resourceinfo/{cmid} GET getResourceInfo end================>"); return entity; }