org.springframework.http.client.ClientHttpRequestExecution Java Examples

The following examples show how to use org.springframework.http.client.ClientHttpRequestExecution. 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: TransactionClientHttpRequestInterceptor.java    From txle with Apache License 2.0 7 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
    ClientHttpRequestExecution execution) throws IOException {

  if (omegaContext != null && omegaContext.globalTxId() != null) {
    request.getHeaders().add(GLOBAL_TX_ID_KEY, omegaContext.globalTxId());
    request.getHeaders().add(LOCAL_TX_ID_KEY, omegaContext.localTxId());
    request.getHeaders().add(GLOBAL_TX_CATEGORY_KEY, omegaContext.category());

    LOG.debug("Added {} {} and {} {} to request header",
        GLOBAL_TX_ID_KEY,
        omegaContext.globalTxId(),
        LOCAL_TX_ID_KEY,
        omegaContext.localTxId(),
        GLOBAL_TX_CATEGORY_KEY,
        omegaContext.category());
  }
  return execution.execute(request, body);
}
 
Example #2
Source File: GrayHttpRequestInterceptor.java    From lion with Apache License 2.0 6 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {

    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest servletRequest = attributes.getRequest();

    // 设置请求头header信息
    Enumeration<String> headerNames = servletRequest.getHeaderNames();
    if (null != headerNames) {
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            String value = servletRequest.getHeader(name);
            // 若version版本号为空,则赋值默认版本号
            if (name.equals(GrayConstant.VERSION) && StringUtils.isEmpty(value)) {
                value = GrayConstant.DEFAULT_VERSION;
            }
            request.getHeaders().add(name, value);
        }
    }

    // 设置灰度版本
    String version = servletRequest.getHeader(GrayConstant.VERSION);
    RibbonFilterContextHolder.getCurrentContext().add(GrayConstant.VERSION, version);

    return execution.execute(request, body);
}
 
Example #3
Source File: RestTemplateHeaderInterceptor.java    From blade-tool with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public ClientHttpResponse intercept(
	HttpRequest request, byte[] bytes,
	ClientHttpRequestExecution execution) throws IOException {
	HttpHeaders headers = BladeHttpHeadersContextHolder.get();
	// 考虑2中情况 1. RestTemplate 不是用 hystrix 2. 使用 hystrix
	if (headers == null) {
		headers = BladeHttpHeadersContextHolder.toHeaders(accountGetter, properties);
	}
	if (headers != null && !headers.isEmpty()) {
		HttpHeaders httpHeaders = request.getHeaders();
		headers.forEach((key, values) -> {
			values.forEach(value -> httpHeaders.add(key, value));
		});
	}
	return execution.execute(request, bytes);
}
 
Example #4
Source File: TransactionClientHttpRequestInterceptor.java    From servicecomb-pack with Apache License 2.0 6 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
    ClientHttpRequestExecution execution) throws IOException {

  if (omegaContext!= null && omegaContext.globalTxId() != null) {
    request.getHeaders().add(GLOBAL_TX_ID_KEY, omegaContext.globalTxId());
    request.getHeaders().add(LOCAL_TX_ID_KEY, omegaContext.localTxId());

    LOG.debug("Added {} {} and {} {} to request header",
        GLOBAL_TX_ID_KEY,
        omegaContext.globalTxId(),
        LOCAL_TX_ID_KEY,
        omegaContext.localTxId());
  } else {
    LOG.debug("Cannot inject transaction ID, as the OmegaContext is null or cannot get the globalTxId.");
  }
  return execution.execute(request, body);
}
 
Example #5
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 #6
Source File: MetricsClientHttpRequestInterceptor.java    From summerframework with Apache License 2.0 6 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
    throws IOException {
    final String urlTemplate = urlTemplateHolder.get();
    urlTemplateHolder.remove();
    final Clock clock = meterRegistry.config().clock();
    final long startTime = clock.monotonicTime();
    IOException ex = null;
    ClientHttpResponse response = null;
    try {
        response = execution.execute(request, body);
        return response;
    } catch (IOException e) {
        ex = e;
        throw e;
    } finally {
        getTimeBuilder(urlTemplate, request, response, ex).register(this.meterRegistry)
            .record(clock.monotonicTime() - startTime, TimeUnit.NANOSECONDS);
    }
}
 
Example #7
Source File: SentinelProtectInterceptor.java    From spring-cloud-alibaba with Apache License 2.0 6 votes vote down vote up
private ClientHttpResponse handleBlockException(HttpRequest request, byte[] body,
		ClientHttpRequestExecution execution, BlockException ex) {
	Object[] args = new Object[] { request, body, execution, ex };
	// handle degrade
	if (isDegradeFailure(ex)) {
		Method fallbackMethod = extractFallbackMethod(sentinelRestTemplate.fallback(),
				sentinelRestTemplate.fallbackClass());
		if (fallbackMethod != null) {
			return (ClientHttpResponse) methodInvoke(fallbackMethod, args);
		}
		else {
			return new SentinelClientHttpResponse();
		}
	}
	// handle flow
	Method blockHandler = extractBlockHandlerMethod(
			sentinelRestTemplate.blockHandler(),
			sentinelRestTemplate.blockHandlerClass());
	if (blockHandler != null) {
		return (ClientHttpResponse) methodInvoke(blockHandler, args);
	}
	else {
		return new SentinelClientHttpResponse();
	}
}
 
Example #8
Source File: TaggingRequestInterceptor.java    From multiapps-controller with Apache License 2.0 5 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
    HttpHeaders headers = request.getHeaders();
    setHeader(headers, TAG_HEADER_NAME, headerValue);
    if (orgHeaderValue != null && spaceHeaderValue != null) {
        setHeader(headers, TAG_HEADER_ORG_NAME, orgHeaderValue);
        setHeader(headers, TAG_HEADER_SPACE_NAME, spaceHeaderValue);
    }
    return execution.execute(request, body);
}
 
Example #9
Source File: UserContextInterceptor.java    From spring-microservices-in-action with Apache License 2.0 5 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
    HttpHeaders headers = request.getHeaders();
    headers.add(UserContext.CORRELATION_ID, UserContextHolder.getContext().getCorrelationId());
    headers.add(UserContext.AUTH_TOKEN,     UserContextHolder.getContext().getAuthToken());

    return execution.execute(request, body);
}
 
Example #10
Source File: AllureRestTemplate.java    From allure-java with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("NullableProblems")
@Override
public ClientHttpResponse intercept(@NonNull final HttpRequest request, final byte[] body,
                                    @NonNull final ClientHttpRequestExecution execution) throws IOException {
    final AttachmentProcessor<AttachmentData> processor = new DefaultAttachmentProcessor();

    final HttpRequestAttachment.Builder requestAttachmentBuilder = HttpRequestAttachment.Builder
            .create("Request", request.getURI().toString())
            .setMethod(request.getMethodValue())
            .setHeaders(toMapConverter(request.getHeaders()));
    if (body.length != 0) {
        requestAttachmentBuilder.setBody(new String(body, StandardCharsets.UTF_8));
    }

    final HttpRequestAttachment requestAttachment = requestAttachmentBuilder.build();
    processor.addAttachment(requestAttachment, new FreemarkerAttachmentRenderer(requestTemplatePath));

    final ClientHttpResponse clientHttpResponse = execution.execute(request, body);

    final HttpResponseAttachment responseAttachment = HttpResponseAttachment.Builder
            .create("Response")
            .setResponseCode(clientHttpResponse.getRawStatusCode())
            .setHeaders(toMapConverter(clientHttpResponse.getHeaders()))
            .setBody(StreamUtils.copyToString(clientHttpResponse.getBody(), StandardCharsets.UTF_8))
            .build();
    processor.addAttachment(responseAttachment, new FreemarkerAttachmentRenderer(responseTemplatePath));

    return clientHttpResponse;
}
 
Example #11
Source File: CredHubOAuth2RequestInterceptor.java    From spring-credhub with Apache License 2.0 5 votes vote down vote up
/**
 * Add an OAuth2 bearer token header to each request.
 *
 * {@inheritDoc}
 */
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
		throws IOException {
	HttpRequestWrapper requestWrapper = new HttpRequestWrapper(request);

	HttpHeaders headers = requestWrapper.getHeaders();
	headers.setBearerAuth(authorizeClient().getAccessToken().getTokenValue());

	return execution.execute(requestWrapper, body);
}
 
Example #12
Source File: CredHubRestTemplateFactory.java    From spring-credhub with Apache License 2.0 5 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
		throws IOException {
	HttpRequestWrapper requestWrapper = new HttpRequestWrapper(request);

	HttpHeaders headers = requestWrapper.getHeaders();
	headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
	headers.setContentType(MediaType.APPLICATION_JSON);

	return execution.execute(requestWrapper, body);
}
 
Example #13
Source File: BasicAuthorizationInterceptor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
		ClientHttpRequestExecution execution) throws IOException {

	String token = Base64Utils.encodeToString((this.username + ":" + this.password).getBytes(UTF_8));
	request.getHeaders().add("Authorization", "Basic " + token);
	return execution.execute(request, body);
}
 
Example #14
Source File: UserContextInterceptor.java    From spring-microservices-in-action with Apache License 2.0 5 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
    HttpHeaders headers = request.getHeaders();
    headers.add(UserContext.CORRELATION_ID, UserContextHolder.getContext().getCorrelationId());
    headers.add(UserContext.AUTH_TOKEN,     UserContextHolder.getContext().getAuthToken());

    return execution.execute(request, body);
}
 
Example #15
Source File: HttpBasicAuthenticationSecurityConfiguration.java    From spring-boot-data-geode with Apache License 2.0 5 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
		ClientHttpRequestExecution execution) throws IOException {

	if (isAuthenticationEnabled()) {

		HttpHeaders requestHeaders = request.getHeaders();

		requestHeaders.add(GeodeConstants.USERNAME, getUsername());
		requestHeaders.add(GeodeConstants.PASSWORD, getPassword());
	}

	return execution.execute(request, body);
}
 
Example #16
Source File: HttpRequestWithPoPSignatureInterceptor.java    From OAuth-2.0-Cookbook with MIT License 5 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
    ClientHttpRequestExecution execution) throws IOException {
    OAuth2ClientContext clientContext = applicationContext.getBean(OAuth2ClientContext.class);
    OAuth2AccessToken accessToken = clientContext.getAccessToken();

    request.getHeaders().set("Authorization", "Bearer " + accessToken.getValue());
    request.getHeaders().set("nonce", keyPairManager.getSignedContent(UUID.randomUUID().toString()));

    return execution.execute(request, body);
}
 
Example #17
Source File: CatRestInterceptor.java    From piggymetrics with MIT License 5 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
		throws IOException {

	Transaction t = Cat.newTransaction(CatConstants.TYPE_REMOTE_CALL, request.getURI().toString());

	try {
		HttpHeaders headers = request.getHeaders();

		// 保存和传递CAT调用链上下文
		Context ctx = new CatContext();
		Cat.logRemoteCallClient(ctx);
		headers.add(CatHttpConstants.CAT_HTTP_HEADER_ROOT_MESSAGE_ID, ctx.getProperty(Cat.Context.ROOT));
		headers.add(CatHttpConstants.CAT_HTTP_HEADER_PARENT_MESSAGE_ID, ctx.getProperty(Cat.Context.PARENT));
		headers.add(CatHttpConstants.CAT_HTTP_HEADER_CHILD_MESSAGE_ID, ctx.getProperty(Cat.Context.CHILD));

		// 保证请求继续被执行
		ClientHttpResponse response =  execution.execute(request, body);
		t.setStatus(Transaction.SUCCESS);
		return response;
	} catch (Exception e) {
		Cat.getProducer().logError(e);
		t.setStatus(e);
		throw e;
	} finally {
		t.complete();
	}
}
 
Example #18
Source File: SentinelRuleLocator.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
                                    ClientHttpRequestExecution execution) throws IOException {
    for (Map.Entry<String, String> header : headers.entrySet()) {
        request.getHeaders().add(header.getKey(), header.getValue());
    }
    return execution.execute(request, body);
}
 
Example #19
Source File: CatRestInterceptor.java    From piggymetrics with MIT License 5 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
		throws IOException {

	Transaction t = Cat.newTransaction(CatConstants.TYPE_REMOTE_CALL, request.getURI().toString());

	try {
		HttpHeaders headers = request.getHeaders();

		// 保存和传递CAT调用链上下文
		Context ctx = new CatContext();
		Cat.logRemoteCallClient(ctx);
		headers.add(CatHttpConstants.CAT_HTTP_HEADER_ROOT_MESSAGE_ID, ctx.getProperty(Cat.Context.ROOT));
		headers.add(CatHttpConstants.CAT_HTTP_HEADER_PARENT_MESSAGE_ID, ctx.getProperty(Cat.Context.PARENT));
		headers.add(CatHttpConstants.CAT_HTTP_HEADER_CHILD_MESSAGE_ID, ctx.getProperty(Cat.Context.CHILD));

		// 保证请求继续被执行
		ClientHttpResponse response =  execution.execute(request, body);
		t.setStatus(Transaction.SUCCESS);
		return response;
	} catch (Exception e) {
		Cat.getProducer().logError(e);
		t.setStatus(e);
		throw e;
	} finally {
		t.complete();
	}
}
 
Example #20
Source File: UserContextInterceptor.java    From spring-microservices-in-action with Apache License 2.0 5 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
    HttpHeaders headers = request.getHeaders();
    headers.add(UserContext.CORRELATION_ID, UserContextHolder.getContext().getCorrelationId());
    headers.add(UserContext.AUTH_TOKEN,     UserContextHolder.getContext().getAuthToken());

    return execution.execute(request, body);
}
 
Example #21
Source File: CatRestInterceptor.java    From piggymetrics with MIT License 5 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
		throws IOException {

	Transaction t = Cat.newTransaction(CatConstants.TYPE_REMOTE_CALL, request.getURI().toString());

	try {
		HttpHeaders headers = request.getHeaders();

		// 保存和传递CAT调用链上下文
		Context ctx = new CatContext();
		Cat.logRemoteCallClient(ctx);
		headers.add(CatHttpConstants.CAT_HTTP_HEADER_ROOT_MESSAGE_ID, ctx.getProperty(Cat.Context.ROOT));
		headers.add(CatHttpConstants.CAT_HTTP_HEADER_PARENT_MESSAGE_ID, ctx.getProperty(Cat.Context.PARENT));
		headers.add(CatHttpConstants.CAT_HTTP_HEADER_CHILD_MESSAGE_ID, ctx.getProperty(Cat.Context.CHILD));

		// 保证请求继续被执行
		ClientHttpResponse response =  execution.execute(request, body);
		t.setStatus(Transaction.SUCCESS);
		return response;
	} catch (Exception e) {
		Cat.getProducer().logError(e);
		t.setStatus(e);
		throw e;
	} finally {
		t.complete();
	}
}
 
Example #22
Source File: UserContextInterceptor.java    From spring-microservices-in-action with Apache License 2.0 5 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
    HttpHeaders headers = request.getHeaders();
    headers.add(UserContext.CORRELATION_ID, UserContextHolder.getContext().getCorrelationId());
    headers.add(UserContext.AUTH_TOKEN,     UserContextHolder.getContext().getAuthToken());

    return execution.execute(request, body);
}
 
Example #23
Source File: UserContextInterceptor.java    From spring-microservices-in-action with Apache License 2.0 5 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
    HttpHeaders headers = request.getHeaders();
    headers.add(UserContext.CORRELATION_ID, UserContextHolder.getContext().getCorrelationId());
    headers.add(UserContext.AUTH_TOKEN,     UserContextHolder.getContext().getAuthToken());

    return execution.execute(request, body);
}
 
Example #24
Source File: CoreHttpRequestInterceptor.java    From paascloud-master with Apache License 2.0 5 votes vote down vote up
/**
 * Intercept client http response.
 *
 * @param request   the request
 * @param body      the body
 * @param execution the execution
 *
 * @return the client http response
 *
 * @throws IOException the io exception
 */
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
                                    ClientHttpRequestExecution execution) throws IOException {
	HttpRequestWrapper requestWrapper = new HttpRequestWrapper(request);

	String header = StringUtils.collectionToDelimitedString(
			CoreHeaderInterceptor.LABEL.get(),
			CoreHeaderInterceptor.HEADER_LABEL_SPLIT);
	log.info("header={} ", header);
	requestWrapper.getHeaders().add(CoreHeaderInterceptor.HEADER_LABEL, header);

	return execution.execute(requestWrapper, body);
}
 
Example #25
Source File: ScmPropertySourceLocator.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
		throws IOException {
	for (Entry<String, String> h : headers.entrySet()) {
		request.getHeaders().add(h.getKey(), h.getValue());
	}
	return execution.execute(request, body);
}
 
Example #26
Source File: GrayClientHttpRequestIntercptor.java    From spring-cloud-gray with Apache License 2.0 5 votes vote down vote up
@Override
    public ClientHttpResponse intercept(
            HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        URI uri = request.getURI();
        GrayHttpRequest grayRequest = new GrayHttpRequest();
        grayRequest.setUri(uri);
        grayRequest.setServiceId(uri.getHost());
        grayRequest.setParameters(WebUtils.getQueryParams(uri.getQuery()));
        if (grayRequestProperties.isLoadBody()) {
            grayRequest.setBody(body);
        }
        grayRequest.setMethod(request.getMethod().name());
        grayRequest.addHeaders(request.getHeaders());

        grayRequest.setAttribute(GRAY_REQUEST_ATTRIBUTE_RESTTEMPLATE_REQUEST, request);
        RoutingConnectPointContext connectPointContext = RoutingConnectPointContext.builder()
                .interceptroType(GrayNetflixClientConstants.INTERCEPTRO_TYPE_RESTTEMPLATE)
                .grayRequest(grayRequest).build();

        return routingConnectionPoint.execute(connectPointContext, () -> execution.execute(request, body));

//        try {
//            ribbonConnectionPoint.executeConnectPoint(connectPointContext);
//            return execution.execute(request, body);
//        } catch (Exception e) {
//            connectPointContext.setThrowable(e);
//            throw e;
//        } finally {
//            ribbonConnectionPoint.shutdownconnectPoint(connectPointContext);
//        }
    }
 
Example #27
Source File: RestTemplateInterceptor.java    From sofa-tracer with Apache License 2.0 5 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
                                    ClientHttpRequestExecution execution) throws IOException {
    SofaTracerSpan sofaTracerSpan = restTemplateTracer.clientSend(request.getMethod().name());
    appendRestTemplateRequestSpanTags(request, sofaTracerSpan);
    ClientHttpResponse response = null;
    Throwable t = null;
    try {
        return response = execution.execute(request, body);
    } catch (IOException e) {
        t = e;
        throw e;
    } finally {
        SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext();
        SofaTracerSpan currentSpan = sofaTraceContext.getCurrentSpan();
        String resultCode = SofaTracerConstant.RESULT_CODE_ERROR;
        // is get error
        if (t != null) {
            currentSpan.setTag(Tags.ERROR.getKey(), t.getMessage());
            // current thread name
            sofaTracerSpan.setTag(CommonSpanTags.CURRENT_THREAD_NAME, Thread.currentThread()
                .getName());
        }
        if (response != null) {
            //tag append
            appendRestTemplateResponseSpanTags(response, currentSpan);
            //finish
            resultCode = String.valueOf(response.getStatusCode().value());
        }
        restTemplateTracer.clientReceive(resultCode);
    }
}
 
Example #28
Source File: ApiClient.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
    logRequest(request, body);
    ClientHttpResponse response = execution.execute(request, body);
    logResponse(response);
    return response;
}
 
Example #29
Source File: ApiClient.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
    logRequest(request, body);
    ClientHttpResponse response = execution.execute(request, body);
    logResponse(response);
    return response;
}
 
Example #30
Source File: ApiClient.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
    logRequest(request, body);
    ClientHttpResponse response = execution.execute(request, body);
    logResponse(response);
    return response;
}