org.springframework.http.HttpRequest.getHeaders()

Here are the examples of the java api org.springframework.http.HttpRequest.getHeaders() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

107 Examples 7

19 View Source File : LoggingContextInterceptorTest.java
License : Apache License 2.0
Project Creator : adorsys

@BeforeEach
void setUp() throws IOException {
    when(mockHttpRequest.getHeaders()).thenReturn(new HttpHeaders());
    when(mockClientHttpRequestExecution.execute(mockHttpRequest, REQUEST_BODY)).thenReturn(mockClientHttpResponse);
}

18 View Source File : RestTemplateRequestCarrier.java
License : Apache License 2.0
Project Creator : sofastack

@Override
public void put(String key, String value) {
    request.getHeaders().add(key, value);
}

18 View Source File : RestTemplateStrategyInterceptor.java
License : Apache License 2.0
Project Creator : Nepxion

private void applyInnerHeader(HttpRequest request) {
    HttpHeaders headers = request.getHeaders();
    headers.add(DiscoveryConstant.N_D_SERVICE_GROUP, pluginAdapter.getGroup());
    headers.add(DiscoveryConstant.N_D_SERVICE_TYPE, pluginAdapter.getServiceType());
    String serviceAppId = pluginAdapter.getServiceAppId();
    if (StringUtils.isNotEmpty(serviceAppId)) {
        headers.add(DiscoveryConstant.N_D_SERVICE_APP_ID, serviceAppId);
    }
    headers.add(DiscoveryConstant.N_D_SERVICE_ID, pluginAdapter.getServiceId());
    headers.add(DiscoveryConstant.N_D_SERVICE_ADDRESS, pluginAdapter.getHost() + ":" + pluginAdapter.getPort());
    headers.add(DiscoveryConstant.N_D_SERVICE_VERSION, pluginAdapter.getVersion());
    headers.add(DiscoveryConstant.N_D_SERVICE_REGION, pluginAdapter.getRegion());
    headers.add(DiscoveryConstant.N_D_SERVICE_ENVIRONMENT, pluginAdapter.getEnvironment());
    headers.add(DiscoveryConstant.N_D_SERVICE_ZONE, pluginAdapter.getZone());
}

18 View Source File : WebUtils.java
License : Apache License 2.0
Project Creator : langtianya

/**
 * Check if the request is a same-origin one, based on {@code Origin}, {@code Host},
 * {@code Forwarded} and {@code X-Forwarded-Host} headers.
 * @return {@code true} if the request is a same-origin one, {@code false} in case
 * of cross-origin request.
 * @since 4.2
 */
public static boolean isSameOrigin(HttpRequest request) {
    String origin = request.getHeaders().getOrigin();
    if (origin == null) {
        return true;
    }
    UriComponents actualUrl = UriComponentsBuilder.fromHttpRequest(request).build();
    UriComponents originUrl = UriComponentsBuilder.fromOriginHeader(origin).build();
    return (actualUrl.getHost().equals(originUrl.getHost()) && getPort(actualUrl) == getPort(originUrl));
}

18 View Source File : TransactionClientHttpRequestInterceptorTest.java
License : Apache License 2.0
Project Creator : apache

@Test
public void keepHeaderUnchangedIfContextAbsent() throws IOException {
    when(request.getHeaders()).thenReturn(new HttpHeaders());
    when(execution.execute(request, null)).thenReturn(response);
    clientHttpRequestInterceptor.intercept(request, null, execution);
    replacedertThat(request.getHeaders().isEmpty(), is(true));
}

17 View Source File : HttpHeaderInterceptor.java
License : Apache License 2.0
Project Creator : yuanmabiji

@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
    request.getHeaders().add(this.name, this.value);
    return execution.execute(request, body);
}

17 View Source File : OAuth2RequestsInterceptor.java
License : Apache License 2.0
Project Creator : xaecbd

@Override
public ClientHttpResponse intercept(final HttpRequest request, final byte[] body, ClientHttpRequestExecution execution) throws IOException {
    HttpRequest protectedResourceRequest = new HttpRequestDecorators(request);
    protectedResourceRequest.getHeaders().set("Authorization", "Bearer " + accessToken);
    return execution.execute(protectedResourceRequest, body);
}

17 View Source File : WebUtils.java
License : MIT License
Project Creator : Vip-Augus

/**
 * Check if the request is a same-origin one, based on {@code Origin}, {@code Host},
 * {@code Forwarded}, {@code X-Forwarded-Proto}, {@code X-Forwarded-Host} and
 * {@code X-Forwarded-Port} headers.
 *
 * <p><strong>Note:</strong> as of 5.1 this method ignores
 * {@code "Forwarded"} and {@code "X-Forwarded-*"} headers that specify the
 * client-originated address. Consider using the {@code ForwardedHeaderFilter}
 * to extract and use, or to discard such headers.
 *
 * @return {@code true} if the request is a same-origin one, {@code false} in case
 * of cross-origin request
 * @since 4.2
 */
public static boolean isSameOrigin(HttpRequest request) {
    HttpHeaders headers = request.getHeaders();
    String origin = headers.getOrigin();
    if (origin == null) {
        return true;
    }
    String scheme;
    String host;
    int port;
    if (request instanceof ServletServerHttpRequest) {
        // Build more efficiently if we can: we only need scheme, host, port for origin comparison
        HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
        scheme = servletRequest.getScheme();
        host = servletRequest.getServerName();
        port = servletRequest.getServerPort();
    } else {
        URI uri = request.getURI();
        scheme = uri.getScheme();
        host = uri.getHost();
        port = uri.getPort();
    }
    UriComponents originUrl = UriComponentsBuilder.fromOriginHeader(origin).build();
    return (ObjectUtils.nullSafeEquals(scheme, originUrl.getScheme()) && ObjectUtils.nullSafeEquals(host, originUrl.getHost()) && getPort(scheme, port) == getPort(originUrl.getScheme(), originUrl.getPort()));
}

17 View Source File : WebUtils.java
License : MIT License
Project Creator : Vip-Augus

/**
 * Check the given request origin against a list of allowed origins.
 * A list containing "*" means that all origins are allowed.
 * An empty list means only same origin is allowed.
 *
 * <p><strong>Note:</strong> as of 5.1 this method ignores
 * {@code "Forwarded"} and {@code "X-Forwarded-*"} headers that specify the
 * client-originated address. Consider using the {@code ForwardedHeaderFilter}
 * to extract and use, or to discard such headers.
 *
 * @return {@code true} if the request origin is valid, {@code false} otherwise
 * @since 4.1.5
 * @see <a href="https://tools.ietf.org/html/rfc6454">RFC 6454: The Web Origin Concept</a>
 */
public static boolean isValidOrigin(HttpRequest request, Collection<String> allowedOrigins) {
    replacedert.notNull(request, "Request must not be null");
    replacedert.notNull(allowedOrigins, "Allowed origins must not be null");
    String origin = request.getHeaders().getOrigin();
    if (origin == null || allowedOrigins.contains("*")) {
        return true;
    } else if (CollectionUtils.isEmpty(allowedOrigins)) {
        return isSameOrigin(request);
    } else {
        return allowedOrigins.contains(origin);
    }
}

17 View Source File : UriComponentsBuilder.java
License : MIT License
Project Creator : Vip-Augus

/**
 * Create a new {@code UriComponents} object from the URI replacedociated with
 * the given HttpRequest while also overlaying with values from the headers
 * "Forwarded" (<a href="https://tools.ietf.org/html/rfc7239">RFC 7239</a>),
 * or "X-Forwarded-Host", "X-Forwarded-Port", and "X-Forwarded-Proto" if
 * "Forwarded" is not found.
 * @param request the source request
 * @return the URI components of the URI
 * @since 4.1.5
 */
public static UriComponentsBuilder fromHttpRequest(HttpRequest request) {
    return fromUri(request.getURI()).adaptFromForwardedHeaders(request.getHeaders());
}

@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] bytes, ClientHttpRequestExecution execution) throws IOException {
    // log the http request
    LOG.info("URI: {}", request.getURI());
    LOG.info("HTTP Method: {}", request.getMethodValue());
    LOG.info("HTTP Headers: {}", request.getHeaders());
    return execution.execute(request, bytes);
}

17 View Source File : RestTemplateGrayHeaderCustomizer.java
License : Apache License 2.0
Project Creator : spring-avengers

@Override
protected void addHeaderToRequest(HttpRequest request, String key, String value) {
    request.getHeaders().set(key, value);
}

17 View Source File : RestTemplateGrayHeaderCustomizer.java
License : Apache License 2.0
Project Creator : spring-avengers

@Override
protected boolean containsKey(HttpRequest request, String key) {
    return request.getHeaders().containsKey(key);
}

17 View Source File : RestTemplateTracer.java
License : Apache License 2.0
Project Creator : open-telemetry

@Override
protected String requestHeader(HttpRequest request, String name) {
    return request.getHeaders().getFirst(name);
}

17 View Source File : RestTemplateStrategyInterceptor.java
License : Apache License 2.0
Project Creator : Nepxion

private void interceptOutputHeader(HttpRequest request) {
    if (!interceptDebugEnabled) {
        return;
    }
    System.out.println("------- " + getInterceptorName() + " Intercept Output Header Information ------");
    HttpHeaders headers = request.getHeaders();
    for (Iterator<Entry<String, List<String>>> iterator = headers.entrySet().iterator(); iterator.hasNext(); ) {
        Entry<String, List<String>> header = iterator.next();
        String headerName = header.getKey();
        boolean isHeaderContains = isHeaderContains(headerName.toLowerCase());
        if (isHeaderContains) {
            List<String> headerValue = header.getValue();
            System.out.println(headerName + "=" + headerValue);
        }
    }
    System.out.println("--------------------------------------------------");
}

17 View Source File : UriComponentsBuilder.java
License : MIT License
Project Creator : mindcarver

/**
 * Create a new {@code UriComponents} object from the URI replacedociated with
 * the given HttpRequest while also overlaying with values from the headers
 * "Forwarded" (<a href="http://tools.ietf.org/html/rfc7239">RFC 7239</a>),
 * or "X-Forwarded-Host", "X-Forwarded-Port", and "X-Forwarded-Proto" if
 * "Forwarded" is not found.
 * @param request the source request
 * @return the URI components of the URI
 * @since 4.1.5
 */
public static UriComponentsBuilder fromHttpRequest(HttpRequest request) {
    return fromUri(request.getURI()).adaptFromForwardedHeaders(request.getHeaders());
}

17 View Source File : JenkinsAuthorizationInterceptor.java
License : MIT License
Project Creator : ls1intum

@NotNull
@Override
public ClientHttpResponse intercept(HttpRequest request, @NotNull byte[] body, @NotNull ClientHttpRequestExecution execution) throws IOException {
    request.getHeaders().setBasicAuth(username, preplacedword);
    if (useCrumb) {
        setCrumb(request.getHeaders());
    }
    return execution.execute(request, body);
}

17 View Source File : GitLabAuthorizationInterceptor.java
License : MIT License
Project Creator : ls1intum

@NotNull
@Override
public ClientHttpResponse intercept(HttpRequest request, @NotNull byte[] body, @NotNull ClientHttpRequestExecution execution) throws IOException {
    request.getHeaders().add("Private-Token", gitlabPrivateToken);
    return execution.execute(request, body);
}

17 View Source File : JiraAuthorizationInterceptor.java
License : MIT License
Project Creator : ls1intum

@NotNull
@Override
public ClientHttpResponse intercept(HttpRequest request, @NotNull byte[] body, @NotNull ClientHttpRequestExecution execution) throws IOException {
    if (!request.getHeaders().containsKey(HttpHeaders.AUTHORIZATION)) {
        request.getHeaders().setBasicAuth(JIRA_USER, JIRA_PreplacedWORD);
    }
    return execution.execute(request, body);
}

17 View Source File : WebUtils.java
License : Apache License 2.0
Project Creator : langtianya

/**
 * Check the given request origin against a list of allowed origins.
 * A list containing "*" means that all origins are allowed.
 * An empty list means only same origin is allowed.
 * @return {@code true} if the request origin is valid, {@code false} otherwise
 * @since 4.1.5
 * @see <a href="https://tools.ietf.org/html/rfc6454">RFC 6454: The Web Origin Concept</a>
 */
public static boolean isValidOrigin(HttpRequest request, Collection<String> allowedOrigins) {
    replacedert.notNull(request, "Request must not be null");
    replacedert.notNull(allowedOrigins, "Allowed origins must not be null");
    String origin = request.getHeaders().getOrigin();
    if (origin == null || allowedOrigins.contains("*")) {
        return true;
    } else if (CollectionUtils.isEmpty(allowedOrigins)) {
        return isSameOrigin(request);
    } else {
        return allowedOrigins.contains(origin);
    }
}

17 View Source File : DtmRestTemplateInterceptor.java
License : Apache License 2.0
Project Creator : huaweicloud

private void exportDtmContextToHeader(HttpRequest httpRequest) {
    if (DtmConstants.DTM_CONTEXT_EX_METHOD == null) {
        return;
    }
    try {
        Object context = DtmConstants.DTM_CONTEXT_EX_METHOD.invoke(null);
        if (context instanceof Map) {
            httpRequest.getHeaders().add(DtmConstants.DTM_CONTEXT, JsonUtils.OBJ_MAPPER.writeValuereplacedtring(context));
        }
    } catch (Throwable e) {
        // ignore
        LOGGER.warn("Failed to export dtm context", e);
    }
}

17 View Source File : BasicJwtInterceptor.java
License : GNU Lesser General Public License v2.1
Project Creator : fanhualei

@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
    System.out.println("get " + token);
    request.getHeaders().add("Authorization", token);
    return execution.execute(request, body);
}

17 View Source File : BasicJwtInterceptor.java
License : GNU Lesser General Public License v2.1
Project Creator : fanhualei

@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
    request.getHeaders().add("Authorization", token);
    return execution.execute(request, body);
}

17 View Source File : GrayInterceptor.java
License : Apache License 2.0
Project Creator : fangjian0423

@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
    if (rule.getType().equalsIgnoreCase("header")) {
        if (request.getHeaders().containsKey(rule.getName())) {
            String value = request.getHeaders().get(rule.getName()).iterator().next();
            if (value.equals(rule.getValue())) {
                RibbonRequestContextHolder.getCurrentContext().put("Gray", Boolean.TRUE.toString());
            }
        }
    } else if (rule.getType().equalsIgnoreCase("param")) {
        String query = request.getURI().getQuery();
        String[] queryKV = query.split("&");
        for (String queryItem : queryKV) {
            String[] queryInfo = queryItem.split("=");
            if (queryInfo[0].equalsIgnoreCase(rule.getName()) && queryInfo[1].equals(rule.getValue())) {
                RibbonRequestContextHolder.getCurrentContext().put("Gray", Boolean.TRUE.toString());
            }
        }
    }
    return execution.execute(request, body);
}

17 View Source File : GrayInterceptor.java
License : Apache License 2.0
Project Creator : fangjian0423

@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
    if (request.getHeaders().containsKey("Gray")) {
        String value = request.getHeaders().getFirst("Gray");
        if (value.equals("true")) {
            RibbonRequestContextHolder.getCurrentContext().put("Gray", Boolean.TRUE.toString());
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            attributes.setAttribute("Gray", Boolean.TRUE.toString(), 0);
        }
    }
    return execution.execute(request, body);
}

17 View Source File : SpringRestRequestHeaderSetter.java
License : Apache License 2.0
Project Creator : elastic

@Override
public void setHeader(String headerName, String headerValue, HttpRequest request) {
    // the org.springframework.http.HttpRequest has only be introduced in 3.1.0
    request.getHeaders().add(headerName, headerValue);
}

17 View Source File : HeaderRequestInterceptor.java
License : Mozilla Public License 2.0
Project Creator : dlmcpaul

@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
    request.getHeaders().add(headerName, headerValue);
    return execution.execute(request, body);
}

17 View Source File : HttpUserAgentInterceptor.java
License : Apache License 2.0
Project Creator : codeabovelab

@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
    request.getHeaders().set("User-Agent", "Haven");
    return execution.execute(request, body);
}

17 View Source File : HttpMessageConverterResolver.java
License : Apache License 2.0
Project Creator : alibaba

public HttpMessageConverterHolder resolve(HttpRequest request, Clreplaced<?> parameterType) {
    HttpMessageConverterHolder httpMessageConverterHolder = null;
    HttpHeaders httpHeaders = request.getHeaders();
    MediaType contentType = httpHeaders.getContentType();
    if (contentType == null) {
        contentType = MediaType.APPLICATION_OCTET_STREAM;
    }
    for (HttpMessageConverter<?> converter : this.messageConverters) {
        if (converter instanceof GenericHttpMessageConverter) {
            GenericHttpMessageConverter genericConverter = (GenericHttpMessageConverter) converter;
            if (genericConverter.canRead(parameterType, parameterType, contentType)) {
                httpMessageConverterHolder = new HttpMessageConverterHolder(contentType, converter);
                break;
            }
        } else {
            if (converter.canRead(parameterType, contentType)) {
                httpMessageConverterHolder = new HttpMessageConverterHolder(contentType, converter);
                break;
            }
        }
    }
    return httpMessageConverterHolder;
}

17 View Source File : KeycloakTokenProducer.java
License : Apache License 2.0
Project Creator : Activiti

@Override
public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
    httpRequest.getHeaders().set(AUTHORIZATION_HEADER, getTokenString());
    return clientHttpRequestExecution.execute(httpRequest, bytes);
}

17 View Source File : HeaderRequestInterceptor.java
License : Apache License 2.0
Project Creator : 360jinrong

@Override
public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
    if (header != null && !header.isEmpty()) {
        httpRequest.getHeaders().addAll(header);
    }
    return clientHttpRequestExecution.execute(httpRequest, bytes);
}

16 View Source File : UserAgentRequestInterceptor.java
License : Apache License 2.0
Project Creator : Zenika

@Override
public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
    httpRequest.getHeaders().set(HttpHeaders.USER_AGENT, applicationName);
    return clientHttpRequestExecution.execute(httpRequest, bytes);
}

16 View Source File : BasicAuthorizationInterceptor.java
License : MIT License
Project Creator : Vip-Augus

@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
    String token = Base64Utils.encodeToString((this.username + ":" + this.preplacedword).getBytes(StandardCharsets.UTF_8));
    request.getHeaders().add("Authorization", "Basic " + token);
    return execution.execute(request, body);
}

@Test
public void securityAwareClientHttpRequestInterceptorSetsHttpRequestHeaders() throws IOException {
    ClientHttpRequestExecution mockExecution = mock(ClientHttpRequestExecution.clreplaced);
    Environment mockEnvironment = mock(Environment.clreplaced);
    when(mockEnvironment.getProperty(eq("spring.data.gemfire.security.username"))).thenReturn("master");
    when(mockEnvironment.getProperty(eq("spring.data.gemfire.security.preplacedword"))).thenReturn("s3cr3t");
    HttpHeaders httpHeaders = new HttpHeaders();
    HttpRequest mockHttpRequest = mock(HttpRequest.clreplaced);
    when(mockHttpRequest.getHeaders()).thenReturn(httpHeaders);
    ClientHttpRequestInterceptor interceptor = new HttpBasicAuthenticationSecurityConfiguration.SecurityAwareClientHttpRequestInterceptor(mockEnvironment);
    byte[] body = new byte[0];
    interceptor.intercept(mockHttpRequest, body, mockExecution);
    replacedertThat(httpHeaders.getFirst(GeodeConstants.USERNAME)).isEqualTo("master");
    replacedertThat(httpHeaders.getFirst(GeodeConstants.PreplacedWORD)).isEqualTo("s3cr3t");
    verify(mockHttpRequest, times(1)).getHeaders();
    verify(mockExecution, times(1)).execute(eq(mockHttpRequest), eq(body));
}

16 View Source File : RestTemplateHeaderModifierInterceptor.java
License : Mozilla Public License 2.0
Project Creator : openMF

@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
    HttpHeaders headers = request.getHeaders();
    headers.remove("Accept-Encoding");
    headers.remove("Accept-Charset");
    headers.remove("Accept");
    return execution.execute(request, body);
}

16 View Source File : BitbucketAuthorizationInterceptor.java
License : MIT License
Project Creator : ls1intum

@NotNull
@Override
public ClientHttpResponse intercept(HttpRequest request, @NotNull byte[] body, @NotNull ClientHttpRequestExecution execution) throws IOException {
    if (request.getHeaders().getAccept().isEmpty()) {
        request.getHeaders().setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    }
    if (request.getHeaders().getContentType() == null) {
        request.getHeaders().setContentType(MediaType.APPLICATION_JSON);
    }
    // prefer bitbucket token if it is available
    if (bitbucketToken.isPresent() && !needsBasicAuth(request)) {
        request.getHeaders().setBearerAuth(bitbucketToken.get());
    } else {
        // the create project request needs basic auth and does not work with personal tokens
        request.getHeaders().setBasicAuth(bitbucketUser, bitbucketPreplacedword);
    }
    return execution.execute(request, body);
}

16 View Source File : BambooAuthorizationInterceptor.java
License : MIT License
Project Creator : ls1intum

@NotNull
@Override
public ClientHttpResponse intercept(HttpRequest request, @NotNull byte[] body, @NotNull ClientHttpRequestExecution execution) throws IOException {
    if (request.getHeaders().getAccept().isEmpty()) {
        request.getHeaders().setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    }
    if (request.getHeaders().getContentType() == null) {
        request.getHeaders().setContentType(MediaType.APPLICATION_JSON);
    }
    // certain Bamboo requests do not support token based authentication, we have to use basic auth then or we need to use cookie authentication
    String uri = request.getURI().toString();
    if (uri.contains(".action") || uri.contains("/artifact/")) {
        request.getHeaders().setBasicAuth(bambooUser, bambooPreplacedword);
    } else {
        // for all other requests, we use the bamboo token because the authentication is faster and also possible in case JIRA is not available
        request.getHeaders().setBearerAuth(bambooToken);
    }
    return execution.execute(request, body);
}

16 View Source File : HttpRequestInterceptor.java
License : GNU Lesser General Public License v3.0
Project Creator : dromara

@Override
public ClientHttpResponse intercept(final HttpRequest request, final byte[] body, final ClientHttpRequestExecution execution) throws IOException {
    request.getHeaders().add(CommonConstant.TX_TRANSACTION_GROUP, TxTransactionLocal.getInstance().getTxGroupId());
    return execution.execute(request, body);
}

16 View Source File : HttpAuthInterceptor.java
License : Apache License 2.0
Project Creator : codeabovelab

@Override
public ClientHttpResponse intercept(final HttpRequest request, final byte[] body, final ClientHttpRequestExecution execution) throws IOException {
    try {
        final HttpHeaders headers = request.getHeaders();
        interceptInner(headers, request);
        return execution.execute(request, body);
    } finally {
        registryName.remove();
    }
}

16 View Source File : HttpAuthInterceptor.java
License : Apache License 2.0
Project Creator : codeabovelab

@Override
public ListenableFuture<ClientHttpResponse> intercept(HttpRequest request, byte[] body, AsyncClientHttpRequestExecution execution) throws IOException {
    try {
        final HttpHeaders headers = request.getHeaders();
        interceptInner(headers, request);
        return execution.executeAsync(request, body);
    } finally {
        registryName.remove();
    }
}

16 View Source File : BmsAuthorizationInterceptor.java
License : Apache License 2.0
Project Creator : baidu

@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
    request.getHeaders().add("X-BMS-APP-NAME", this.appName);
    request.getHeaders().add("X-BMS-PAAS-TYPE", this.paasType);
    request.getHeaders().add("X-BMS-PLATFORM-NAME", this.platformName);
    // add api version to header
    request.getHeaders().add("X-BMS-API-VERSION", BmsCommonInterceptor.VERSION);
    return execution.execute(request, body);
}

16 View Source File : TransactionClientHttpRequestInterceptorTest.java
License : Apache License 2.0
Project Creator : apache

@Test
public void interceptTransactionIdInHeaderIfContextPresent() throws IOException {
    omegaContext.setGlobalTxId(globalTxId);
    omegaContext.setLocalTxId(localTxId);
    HttpHeaders headers = new HttpHeaders();
    when(request.getHeaders()).thenReturn(headers);
    when(execution.execute(request, null)).thenReturn(response);
    clientHttpRequestInterceptor.intercept(request, null, execution);
    replacedertThat(request.getHeaders().get(OmegaContext.GLOBAL_TX_ID_KEY), contains(globalTxId));
    replacedertThat(request.getHeaders().get(OmegaContext.LOCAL_TX_ID_KEY), contains(localTxId));
}

15 View Source File : ClientHttpRequestInterceptorImpl.java
License : Apache License 2.0
Project Creator : yin5980280

/**
 * (non-Javadoc)
 *
 * @see org.springframework.http.client.ClientHttpRequestInterceptor#intercept
 * (org.springframework.http.HttpRequest, byte[],
 * org.springframework.http.client.ClientHttpRequestExecution)
 */
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
    HttpHeaders headers = request.getHeaders();
    long start = System.currentTimeMillis();
    EnhancerClientHttpResponse response = null;
    try {
        response = new EnhancerClientHttpResponse(execution.execute(request, body));
    } finally {
        String respText = response == null ? "" : response.responseText();
        int status = response == null ? 400 : response.getRawStatusCode();
        log.info("请求地址: [{}], 请求头信息: [{}], 请求参数: [{}] => 请求状态: [{}], 返回结果: [{}]. 请求花费: [{}]毫秒.", request.getURI().toString(), new ObjectMapper().writeValuereplacedtring(headers.entrySet()), new String(body), status, respText, System.currentTimeMillis() - start);
    }
    return response;
}

15 View Source File : BasicAuthenticationInterceptor.java
License : MIT License
Project Creator : Vip-Augus

@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.preplacedword, this.charset);
    }
    return execution.execute(request, body);
}

protected void logRequest(HttpRequest request, byte[] body) {
    log.info("Request: {}", ObjectJoiner.join(" ", request.getURI().getScheme(), request.getMethod(), request.getURI()));
    final boolean hasRequestBody = body != null && body.length > 0;
    if (log.isDebugEnabled()) {
        // If the request has a body, sometimes these headers are not
        // present, so let's make them explicit
        if (hasRequestBody) {
            logHeader(CONTENT_LENGTH_HEADER, Long.toString(body.length));
            final MediaType contentType = request.getHeaders().getContentType();
            if (contentType != null) {
                logHeader(CONTENT_TYPE_HEADER, contentType.toString());
            }
        }
        // Log the other headers
        for (String header : request.getHeaders().keySet()) {
            if (!CONTENT_TYPE_HEADER.equalsIgnoreCase(header) && !CONTENT_LENGTH_HEADER.equalsIgnoreCase(header)) {
                for (String value : request.getHeaders().get(header)) {
                    logHeader(header, value);
                }
            }
        }
        if (log.isTraceEnabled() && hasRequestBody) {
            logBody(new String(body, determineCharset(request.getHeaders())), request.getHeaders());
        }
    }
}

15 View Source File : LoggingRequestInterceptor.java
License : Apache License 2.0
Project Creator : telstra

private String genereateCurl(HttpRequest request, byte[] payload) throws IOException {
    StringBuilder sb = new StringBuilder();
    sb.append(format("curl -X %s \\\n", request.getMethodValue()));
    sb.append(request.getURI().toString()).append(" \\\n");
    request.getHeaders().forEach((k, v) -> sb.append(format("-H '%s: %s' \\\n", k, StringUtils.substringBetween(v.toString(), "[", "]"))));
    String body = new String(payload, "UTF-8");
    if (!StringUtils.isEmpty(body)) {
        sb.append(format("-d '%s' \n", toJson(body)));
    }
    return sb.toString();
}

15 View Source File : RestTemplateUserContextInterceptor.java
License : Apache License 2.0
Project Creator : SpringCloud

@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
    User user = UserContextHolder.currentUser();
    request.getHeaders().add("x-user-id", user.getUserId());
    request.getHeaders().add("x-user-name", user.getUserName());
    request.getHeaders().add("x-user-serviceName", request.getURI().getHost());
    return execution.execute(request, body);
}

@Test
public void securityAwareClientHttpRequestInterceptorWillNotSetHttpRequestHeadersWhenCredentialsAreIncomplete() throws IOException {
    ClientHttpRequestExecution mockExecution = mock(ClientHttpRequestExecution.clreplaced);
    Environment mockEnvironment = mock(Environment.clreplaced);
    when(mockEnvironment.getProperty(eq("spring.data.gemfire.security.username"))).thenReturn("master");
    HttpHeaders httpHeaders = new HttpHeaders();
    HttpRequest mockHttpRequest = mock(HttpRequest.clreplaced);
    when(mockHttpRequest.getHeaders()).thenReturn(httpHeaders);
    ClientHttpRequestInterceptor interceptor = new HttpBasicAuthenticationSecurityConfiguration.SecurityAwareClientHttpRequestInterceptor(mockEnvironment);
    byte[] body = new byte[0];
    interceptor.intercept(mockHttpRequest, body, mockExecution);
    replacedertThat(httpHeaders.containsKey(GeodeConstants.USERNAME)).isFalse();
    replacedertThat(httpHeaders.containsKey(GeodeConstants.PreplacedWORD)).isFalse();
    verify(mockHttpRequest, never()).getHeaders();
    verify(mockExecution, times(1)).execute(eq(mockHttpRequest), eq(body));
}

15 View Source File : BasicAuthenticationInterceptor.java
License : Apache License 2.0
Project Creator : SourceHot

@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
    HttpHeaders headers = request.getHeaders();
    if (!headers.containsKey(HttpHeaders.AUTHORIZATION)) {
        headers.setBasicAuth(this.encodedCredentials);
    }
    return execution.execute(request, body);
}

15 View Source File : RestTemplateInterceptor.java
License : Apache License 2.0
Project Creator : sofastack

/**
 * add request tag
 * @param request
 * @param sofaTracerSpan
 */
private void appendRestTemplateRequestSpanTags(HttpRequest request, SofaTracerSpan sofaTracerSpan) {
    if (sofaTracerSpan == null) {
        return;
    }
    // appName
    String appName = SofaTracerConfiguration.getProperty(SofaTracerConfiguration.TRACER_APPNAME_KEY, StringUtils.EMPTY_STRING);
    // methodName
    String methodName = request.getMethod().name();
    // appName
    sofaTracerSpan.setTag(CommonSpanTags.LOCAL_APP, appName == null ? StringUtils.EMPTY_STRING : appName);
    sofaTracerSpan.setTag(CommonSpanTags.REQUEST_URL, request.getURI().toString());
    // method
    sofaTracerSpan.setTag(CommonSpanTags.METHOD, methodName);
    HttpHeaders headers = request.getHeaders();
    // reqSize
    if (headers != null && headers.containsKey("Content-Length")) {
        List<String> contentLengthList = headers.get("Content-Length");
        if (contentLengthList != null && !contentLengthList.isEmpty()) {
            sofaTracerSpan.setTag(CommonSpanTags.REQ_SIZE, Long.valueOf(contentLengthList.get(0)));
        }
    } else {
        sofaTracerSpan.setTag(CommonSpanTags.REQ_SIZE, String.valueOf(-1));
    }
    // carrier
    this.injectCarrier(request, sofaTracerSpan);
}

See More Examples