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

The following examples show how to use org.springframework.http.HttpHeaders#containsKey() . 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: BasicAuthenticationInterceptor.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public ClientHttpResponse intercept(
		HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {

	HttpHeaders headers = request.getHeaders();
	if (!headers.containsKey(HttpHeaders.AUTHORIZATION)) {
		headers.setBasicAuth(this.username, this.password, this.charset);
	}
	return execution.execute(request, body);
}
 
Example 2
Source File: Resilience4JCircuitBreakerIntegrationTest.java    From spring-cloud-circuitbreaker with Apache License 2.0 6 votes vote down vote up
@GetMapping("/slowOnDemand")
public String slowOnDemand(@RequestHeader HttpHeaders headers) {
	if (headers.containsKey("delayInMilliseconds")) {
		String delayString = headers.getFirst("delayInMilliseconds");
		if (delayString != null) {
			try {
				Thread.sleep(Integer.parseInt(delayString));
			}
			catch (NumberFormatException | InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	return "normal";
}
 
Example 3
Source File: TraceRequestHttpHeadersFilter.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@Override
public HttpHeaders filter(HttpHeaders input, ServerWebExchange exchange) {
	if (log.isDebugEnabled()) {
		log.debug("Will instrument the HTTP request headers ["
				+ exchange.getRequest().getHeaders() + "]");
	}
	HttpClientRequest request = new HttpClientRequest(exchange.getRequest(), input);
	Span currentSpan = currentSpan(request);
	Span span = injectedSpan(request, currentSpan);
	if (log.isDebugEnabled()) {
		log.debug(
				"Client span  " + span + " created for the request. New headers are "
						+ request.filteredHeaders.toSingleValueMap());
	}
	exchange.getAttributes().put(SPAN_ATTRIBUTE, span);
	HttpHeaders headersWithInput = new HttpHeaders();
	headersWithInput.addAll(input);
	addHeadersWithInput(request.filteredHeaders, headersWithInput);
	if (headersWithInput.containsKey("b3") || headersWithInput.containsKey("B3")) {
		headersWithInput.keySet().remove("b3");
		headersWithInput.keySet().remove("B3");
	}
	return headersWithInput;
}
 
Example 4
Source File: RequestContextHeaderInterceptor.java    From logging-log4j-audit with Apache License 2.0 6 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] body,
                                    ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
    Map<String, String> map = ThreadContext.getImmutableContext();
    HttpHeaders headers = httpRequest.getHeaders();
    for (Map.Entry<String, String> entry : map.entrySet()) {
        RequestContextMapping mapping = mappings.getMapping(entry.getKey());
        if (mapping != null && !mapping.isLocal()) {
            String key = mappings.getHeaderPrefix() + mapping.getFieldName();
            if (!headers.containsKey(key)) {
                headers.add(key, entry.getValue());
            }
        }
    }
    return clientHttpRequestExecution.execute(httpRequest, body);
}
 
Example 5
Source File: WebSocketConfig.java    From bearchoke with Apache License 2.0 6 votes vote down vote up
@Override
protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, Map<String, Object> attributes) {
    Principal result = null;
    String authToken = null;
    HttpHeaders headers = request.getHeaders();

    if (log.isDebugEnabled()) {
        log.debug("Determining user...");
    }

    if (headers.containsKey(ServerConstants.X_AUTH_TOKEN)) {
        authToken = headers.getFirst(ServerConstants.X_AUTH_TOKEN);
        authenticate(authToken);
    } else if (attributes.containsKey(ServerConstants.X_AUTH_TOKEN)) {
        authToken = (String) attributes.get(ServerConstants.X_AUTH_TOKEN);

        authenticate(authToken);
    } else {
        result = super.determineUser(request, wsHandler, attributes);
    }

    return result;
}
 
Example 6
Source File: AbstractRestTemplateClient.java    From documentum-rest-client-java with Apache License 2.0 6 votes vote down vote up
private void setupCSRFClientToken(HttpHeaders headers) {
    if(enableCSRFClientToken) {
        String cookie = headers.getFirst(HttpHeaders.SET_COOKIE);
        if(cookie != null) {
            if(CLIENT_TOKEN_NAME.equals(cookie.substring(0, cookie.indexOf('=')))) {
                clientToken = cookie.substring(cookie.indexOf('=') + 1, cookie.indexOf(','));
                if(debug) {
                    Debug.debug(CLIENT_TOKEN_NAME + "=" + clientToken);
                }
            }
        }
        if(headers.containsKey(CSRF_HEADER_NAME_HEADER)) {
            csrfHeader = headers.getFirst(CSRF_HEADER_NAME_HEADER);
            if(csrfHeader != null) {
                csrfToken = headers.getFirst(csrfHeader);
                if(debug) {
                    Debug.debug(csrfHeader + "=" + csrfToken);
                }
            }
        }
    }
}
 
Example 7
Source File: WxApiHttpResponse.java    From FastBootWeixin with Apache License 2.0 5 votes vote down vote up
/**
 * 你问我为什么要偷梁换柱?当然是因为微信接口返回的是JSON,但是Content-Type却是Text_Pain啦,是否要考虑判断内容?
 * 暂时不需要,除非有些接口返回XML,也是这个头,那就坑爹了
 *
 * @return the result
 */
@Override
public HttpHeaders getHeaders() {
    HttpHeaders headers = this.delegate.getHeaders();
    if (headers.containsKey(HttpHeaders.CONTENT_DISPOSITION)) {
        return headers;
    }
    if (headers.containsKey(HttpHeaders.CONTENT_TYPE) && headers.getContentType().equals(MediaType.TEXT_PLAIN)) {
        headers.setContentType(MediaType.APPLICATION_JSON);
    }
    if (!headers.containsKey(WxWebUtils.X_WX_REQUEST_URL)) {
        headers.add(WxWebUtils.X_WX_REQUEST_URL, request.getURI().toString());
    }
    return headers;
}
 
Example 8
Source File: AbstractMessageConverterMethodProcessor.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Check if the path has a file extension and whether the extension is
 * either {@link #WHITELISTED_EXTENSIONS whitelisted} or explicitly
 * {@link ContentNegotiationManager#getAllFileExtensions() registered}.
 * If not, and the status is in the 2xx range, a 'Content-Disposition'
 * header with a safe attachment file name ("f.txt") is added to prevent
 * RFD exploits.
 */
private void addContentDispositionHeader(ServletServerHttpRequest request, ServletServerHttpResponse response) {
	HttpHeaders headers = response.getHeaders();
	if (headers.containsKey(HttpHeaders.CONTENT_DISPOSITION)) {
		return;
	}

	try {
		int status = response.getServletResponse().getStatus();
		if (status < 200 || status > 299) {
			return;
		}
	}
	catch (Throwable ex) {
		// ignore
	}

	HttpServletRequest servletRequest = request.getServletRequest();
	String requestUri = rawUrlPathHelper.getOriginatingRequestUri(servletRequest);

	int index = requestUri.lastIndexOf('/') + 1;
	String filename = requestUri.substring(index);
	String pathParams = "";

	index = filename.indexOf(';');
	if (index != -1) {
		pathParams = filename.substring(index);
		filename = filename.substring(0, index);
	}

	filename = decodingUrlPathHelper.decodeRequestString(servletRequest, filename);
	String ext = StringUtils.getFilenameExtension(filename);

	pathParams = decodingUrlPathHelper.decodeRequestString(servletRequest, pathParams);
	String extInPathParams = StringUtils.getFilenameExtension(pathParams);

	if (!safeExtension(servletRequest, ext) || !safeExtension(servletRequest, extInPathParams)) {
		headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline;filename=f.txt");
	}
}
 
Example 9
Source File: AbstractNcssController.java    From tds with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected void setResponseHeaders(HttpServletResponse response, HttpHeaders httpHeaders) {
  Set<String> keySet = httpHeaders.keySet();
  for (String key : keySet) {
    if (httpHeaders.containsKey(key)) { // LOOK why test again?
      response.setHeader(key, httpHeaders.get(key).get(0)); // LOOK why only first one ?
    }
  }
}
 
Example 10
Source File: ForwardedHeaderTransformer.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Whether the request has any Forwarded headers.
 * @param request the request
 */
protected boolean hasForwardedHeaders(ServerHttpRequest request) {
	HttpHeaders headers = request.getHeaders();
	for (String headerName : FORWARDED_HEADER_NAMES) {
		if (headers.containsKey(headerName)) {
			return true;
		}
	}
	return false;
}
 
Example 11
Source File: BasicAuthenticationInterceptor.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public ClientHttpResponse intercept(
		HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {

	HttpHeaders headers = request.getHeaders();
	if (!headers.containsKey(HttpHeaders.AUTHORIZATION)) {
		headers.setBasicAuth(this.username, this.password, this.charset);
	}
	return execution.execute(request, body);
}
 
Example 12
Source File: VertxClientHttpRequest.java    From vertx-spring-boot with Apache License 2.0 5 votes vote down vote up
@Override
protected void applyHeaders() {
    HttpHeaders headers = getHeaders();
    if (!headers.containsKey(HttpHeaders.CONTENT_LENGTH)) {
        logger.debug("Setting chunked request");
        delegate.setChunked(true);
    }
    headers.forEach(delegate::putHeader);
}
 
Example 13
Source File: RestTemplateFactory.java    From multiapps-controller with Apache License 2.0 5 votes vote down vote up
@Override
public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
    ClientHttpRequest request = requestFactory.createRequest(uri, httpMethod);
    HttpHeaders requestHeaders = request.getHeaders();
    if (!requestHeaders.containsKey(HttpHeaders.AUTHORIZATION)) {
        requestHeaders.add(HttpHeaders.AUTHORIZATION, "Bearer " + computeAuthorizationToken());
    }
    return request;
}
 
Example 14
Source File: HeaderExpression.java    From spring-cloud-alibaba with Apache License 2.0 4 votes vote down vote up
@Override
protected boolean matchName(HttpRequest request) {
	HttpHeaders httpHeaders = request.getHeaders();
	return httpHeaders.containsKey(this.name);
}
 
Example 15
Source File: AbstractMessageConverterMethodProcessor.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
/**
 * Check if the path has a file extension and whether the extension is
 * either {@link #WHITELISTED_EXTENSIONS whitelisted} or explicitly
 * {@link ContentNegotiationManager#getAllFileExtensions() registered}.
 * If not, and the status is in the 2xx range, a 'Content-Disposition'
 * header with a safe attachment file name ("f.txt") is added to prevent
 * RFD exploits.
 */
private void addContentDispositionHeader(ServletServerHttpRequest request,
		ServletServerHttpResponse response) {

	HttpHeaders headers = response.getHeaders();
	if (headers.containsKey(HttpHeaders.CONTENT_DISPOSITION)) {
		return;
	}

	try {
		int status = response.getServletResponse().getStatus();
		if (status < 200 || status > 299) {
			return;
		}
	}
	catch (Throwable ex) {
		// Ignore
	}

	HttpServletRequest servletRequest = request.getServletRequest();
	String requestUri = RAW_URL_PATH_HELPER.getOriginatingRequestUri(servletRequest);

	int index = requestUri.lastIndexOf('/') + 1;
	String filename = requestUri.substring(index);
	String pathParams = "";

	index = filename.indexOf(';');
	if (index != -1) {
		pathParams = filename.substring(index);
		filename = filename.substring(0, index);
	}

	filename = DECODING_URL_PATH_HELPER.decodeRequestString(servletRequest, filename);
	String ext = StringUtils.getFilenameExtension(filename);

	pathParams = DECODING_URL_PATH_HELPER.decodeRequestString(servletRequest, pathParams);
	String extInPathParams = StringUtils.getFilenameExtension(pathParams);

	if (!safeExtension(servletRequest, ext) || !safeExtension(servletRequest, extInPathParams)) {
		headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline;filename=f.txt");
	}
}
 
Example 16
Source File: TaggingRequestInterceptor.java    From multiapps-controller with Apache License 2.0 4 votes vote down vote up
private void setHeader(HttpHeaders headers, String tagHeaderName, String headerValue) {
    if (headers.containsKey(tagHeaderName)) {
        return;
    }
    headers.add(tagHeaderName, headerValue);
}
 
Example 17
Source File: ContractExchangeHandler.java    From spring-cloud-contract with Apache License 2.0 4 votes vote down vote up
@Override
public HttpHeader header(String key) {
	HttpHeaders headers = this.result.getRequestHeaders();
	return headers.containsKey(key)
			? new HttpHeader(key, headers.getValuesAsList(key)) : null;
}
 
Example 18
Source File: VaultClients.java    From spring-vault with Apache License 2.0 4 votes vote down vote up
/**
 * Create a {@link ClientHttpRequestInterceptor} that associates each request with a
 * {@code X-Vault-Namespace} header if the header is not present.
 * @param namespace the Vault namespace to use. Must not be {@literal null} or empty.
 * @return the {@link ClientHttpRequestInterceptor} to register with
 * {@link RestTemplate}.
 * @see VaultHttpHeaders#VAULT_NAMESPACE
 * @since 2.2
 */
public static ClientHttpRequestInterceptor createNamespaceInterceptor(String namespace) {

	Assert.hasText(namespace, "Vault Namespace must not be empty!");

	return (request, body, execution) -> {

		HttpHeaders headers = request.getHeaders();

		if (!headers.containsKey(VaultHttpHeaders.VAULT_NAMESPACE)) {
			headers.add(VaultHttpHeaders.VAULT_NAMESPACE, namespace);
		}

		return execution.execute(request, body);
	};
}
 
Example 19
Source File: XForwardedHeadersFilter.java    From spring-cloud-gateway with Apache License 2.0 4 votes vote down vote up
private boolean hasHeader(ServerHttpRequest request, String name) {
	HttpHeaders headers = request.getHeaders();
	return headers.containsKey(name) && StringUtils.hasLength(headers.getFirst(name));
}
 
Example 20
Source File: GzipWebFilter.java    From influx-proxy with Apache License 2.0 4 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) {

    HttpHeaders headers = serverWebExchange.getRequest().getHeaders();
    boolean debugCount = headers.containsKey("x-mid") && headers.containsKey("x-debug");
    if (debugCount) {
        log.info("On received x-mid {}, contentLength {}, path {}", headers.get("x-mid"), serverWebExchange.getRequest().getHeaders().getContentLength(), serverWebExchange.getRequest().getQueryParams());
    }
    if (Optional.ofNullable(serverWebExchange.getRequest().getHeaders().get("Content-Encoding"))
            .orElse(Collections.emptyList()).stream()
            .anyMatch(s -> s.toLowerCase().contains("gzip"))) {
        // 解压body,并重新设置content-length

        if (debugCount) {
            log.info("header {}", serverWebExchange.getRequest().getHeaders());
        }
        return serverWebExchange.getRequest().getBody()
                .collectList()
                .map(dataBuffers -> {
                    Assert.notEmpty(dataBuffers, "DataBuffers");
                    if (debugCount) {
                        log.info("On body input x-mid {} , dataBuffers {}", headers.get("x-mid"), dataBuffers.size());
                    }
                    return dataBuffers.get(0).factory().join(dataBuffers);
                })
                .flatMap(dataBuffer -> {
                    try (GZIPInputStream gzipInputStream = new GZIPInputStream(dataBuffer.asInputStream(true))) {
                        byte[] byteBody = ByteStreams.toByteArray(gzipInputStream);
                        if (debugCount) {
                            log.info("On body input x-mid {}, byteBody {}", headers.get("x-mid"), byteBody.length);
                        }
                        return webFilterChain.filter(serverWebExchange.mutate()
                                .request(new ServerHttpRequestDecorator(serverWebExchange.getRequest()) {
                                    @Override
                                    public Flux<DataBuffer> getBody() {
                                        return Flux.just(dataBuffer.factory().wrap(byteBody));
                                    }

                                    @Override
                                    public HttpHeaders getHeaders() {
                                        long contentLength = super.getHeaders().getContentLength();
                                        HttpHeaders httpHeaders = new HttpHeaders();
                                        httpHeaders.putAll(super.getHeaders());
                                        // 由于修改了传递参数,需要重新设置CONTENT_LENGTH,长度是字节长度,不是字符串长度
                                        httpHeaders.remove(HttpHeaders.CONTENT_LENGTH);
                                        if (contentLength > 0) {
                                            httpHeaders.setContentLength(byteBody.length);
                                        } else {
                                            // TODO: this causes a 'HTTP/1.1 411 Length Required' on httpbin.org
                                            httpHeaders.set(HttpHeaders.TRANSFER_ENCODING, "chunked");
                                        }
                                        return httpHeaders;
                                    }
                                })
                                .build());
                    } catch (IOException e) {
                        log.error(e.getMessage(), e);
                        return Mono.error(e);
                    }
                })
                .then();
    }
    return webFilterChain.filter(serverWebExchange);
}