Java Code Examples for org.springframework.http.client.ClientHttpRequestExecution#execute()

The following examples show how to use org.springframework.http.client.ClientHttpRequestExecution#execute() . 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: 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 3
Source File: SampleTests.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 {

	ClientHttpResponse response = execution.execute(request, body);
	byte[] expected = FileCopyUtils.copyToByteArray(this.resource.getInputStream());
	byte[] actual = FileCopyUtils.copyToByteArray(response.getBody());
	assertEquals(new String(expected), new String(actual));
	return response;
}
 
Example 4
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 5
Source File: BasicAuthorizationInterceptor.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 {

	String token = Base64Utils.encodeToString(
			(this.username + ":" + this.password).getBytes(StandardCharsets.UTF_8));
	request.getHeaders().add("Authorization", "Basic " + token);
	return execution.execute(request, body);
}
 
Example 6
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 7
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 8
Source File: RestTemplateCircuitBreakerInterceptor.java    From spring-cloud-formula with Apache License 2.0 5 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes,
                                    ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
    URI asUri = httpRequest.getURI();
    String httpMethod = httpRequest.getMethod().toString();
    String serviceName = asUri.getHost();
    String url = asUri.getPath();
    logger.info("http with serviceName:{}, menthod:{}, url:{}", serviceName, httpMethod, url);
    if (circuitBreakerCore.checkRulesExist(httpMethod, serviceName, url)) {
        try {
            Method wrappedMethod = RestTemplateCircuitBreakerInterceptor.class.getMethod(
                    "doExecute", ClientHttpRequestExecution.class, HttpRequest.class, byte[].class);
            Object[] args = {clientHttpRequestExecution, httpRequest, bytes};
            ClientHttpResponse response = (ClientHttpResponse) circuitBreakerCore.process(httpMethod,
                    serviceName, url, wrappedMethod, this, args);
            // todo 熔断返回null
            return response;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            if (e instanceof CircuitBreakerOpenException) {
                throw  new RuntimeException(e.getMessage());
            } else if (e instanceof IOException) {
                throw  new IOException(e.getMessage());
            } else {
                throw new RuntimeException(e.getMessage());
            }
        }
    } else {
        return clientHttpRequestExecution.execute(httpRequest, bytes);
    }
}
 
Example 9
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 10
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 11
Source File: CustomClientHttpRequestInterceptor.java    From sfg-blog-posts with GNU General Public License v3.0 5 votes vote down vote up
@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);
}
 
Example 12
Source File: TraceClientHttpRequestInterceptor.java    From log-trace-spring-boot with Apache License 2.0 5 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
    HttpHeaders headers = httpRequest.getHeaders();
    Map<String, String> copyOfContextMap = traceContentFactory.assemblyTraceContent();
    for (Map.Entry<String, String> copyOfContext : copyOfContextMap.entrySet()) {
        headers.add(copyOfContext.getKey(), copyOfContext.getValue());
    }
    return clientHttpRequestExecution.execute(httpRequest, bytes);
}
 
Example 13
Source File: TransactionHttpRequestInterceptor.java    From tx-lcn with Apache License 2.0 5 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
    TxTransactionLocal txTransactionLocal = TxTransactionLocal.current();
    String groupId = txTransactionLocal==null?null:txTransactionLocal.getGroupId();
    request.getHeaders().add("tx-group",groupId);
    if (txTransactionLocal != null) {
        if (txTransactionLocal.isHasCompensate()) {
            request.getHeaders().add("tx-group", CompensateService.COMPENSATE_KEY);
        } else {
            request.getHeaders().add("tx-group",groupId);
        }
    }
    return execution.execute(request,body);
}
 
Example 14
Source File: RestTemplateTracingTransmitter.java    From tx-lcn with Apache License 2.0 5 votes vote down vote up
@Override
@NonNull
public ClientHttpResponse intercept(
        @NonNull HttpRequest httpRequest, @NonNull byte[] bytes,
        @NonNull ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
    Tracings.transmit(httpRequest.getHeaders()::add);
    return clientHttpRequestExecution.execute(httpRequest, bytes);
}
 
Example 15
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 16
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 17
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 18
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 19
Source File: DtmRestTemplateInterceptor.java    From spring-cloud-huawei with Apache License 2.0 5 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes,
    ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
  DTMContext dtmContext = DTMContext.getDTMContext();
  long gid = dtmContext.getGlobalTxId();
  HttpHeaders headers = httpRequest.getHeaders();
  if (gid != -1) {
    DtmContextDTO dtmContextDTO = DtmContextDTO.fromDtmContext(dtmContext);
    headers.add(DtmConstants.DTM_CONTEXT, Json.encode(dtmContextDTO));
  }
  return clientHttpRequestExecution.execute(httpRequest, bytes);
}
 
Example 20
Source File: RouterRestTemplateIntercptor.java    From spring-cloud-huawei with Apache License 2.0 3 votes vote down vote up
/**
 * header pass
 *
 * @param httpRequest
 * @param bytes
 * @param clientHttpRequestExecution
 * @return
 * @throws IOException
 */
@Override
public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes,
    ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
  RouterTrackContext.setServiceName(httpRequest.getURI().getHost());
  HttpHeaders headers = httpRequest.getHeaders();
  headers.add(ROUTER_HEADER, HeaderPassUtil.getPassHeaderString(headers.toSingleValueMap()));
  return clientHttpRequestExecution.execute(httpRequest, bytes);
}