org.springframework.http.HttpRequest#getURI ( )源码实例Demo

下面列出了org.springframework.http.HttpRequest#getURI ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@Override
public ListenableFuture<ClientHttpResponse> executeAsync(HttpRequest request, byte[] body)
		throws IOException {

	if (this.iterator.hasNext()) {
		AsyncClientHttpRequestInterceptor interceptor = this.iterator.next();
		return interceptor.intercept(request, body, this);
	}
	else {
		URI uri = request.getURI();
		HttpMethod method = request.getMethod();
		HttpHeaders headers = request.getHeaders();

		Assert.state(method != null, "No standard HTTP method");
		AsyncClientHttpRequest delegate = requestFactory.createAsyncRequest(uri, method);
		delegate.getHeaders().putAll(headers);
		if (body.length > 0) {
			StreamUtils.copy(body, delegate.getBody());
		}

		return delegate.executeAsync();
	}
}
 
@Override
public ListenableFuture<ClientHttpResponse> executeAsync(HttpRequest request, byte[] body)
		throws IOException {

	if (this.iterator.hasNext()) {
		AsyncClientHttpRequestInterceptor interceptor = this.iterator.next();
		return interceptor.intercept(request, body, this);
	}
	else {
		URI uri = request.getURI();
		HttpMethod method = request.getMethod();
		HttpHeaders headers = request.getHeaders();

		Assert.state(method != null, "No standard HTTP method");
		AsyncClientHttpRequest delegate = requestFactory.createAsyncRequest(uri, method);
		delegate.getHeaders().putAll(headers);
		if (body.length > 0) {
			StreamUtils.copy(body, delegate.getBody());
		}

		return delegate.executeAsync();
	}
}
 
源代码3 项目: lams   文件: InterceptingAsyncClientHttpRequest.java
@Override
public ListenableFuture<ClientHttpResponse> executeAsync(HttpRequest request, byte[] body)
		throws IOException {

	if (this.iterator.hasNext()) {
		AsyncClientHttpRequestInterceptor interceptor = this.iterator.next();
		return interceptor.intercept(request, body, this);
	}
	else {
		URI uri = request.getURI();
		HttpMethod method = request.getMethod();
		HttpHeaders headers = request.getHeaders();

		AsyncClientHttpRequest delegate = requestFactory.createAsyncRequest(uri, method);
		delegate.getHeaders().putAll(headers);
		if (body.length > 0) {
			StreamUtils.copy(body, delegate.getBody());
		}

		return delegate.executeAsync();
	}
}
 
源代码4 项目: haven-platform   文件: HttpAuthInterceptor.java
private void interceptInner(HttpHeaders headers, HttpRequest httpRequest) {
    URI uri = httpRequest.getURI();
    String host = uri.getHost();
    int port = uri.getPort();
    String url = host + (port == -1 ? "" : ":" + port);
    String name = registryName.get();
    log.debug("try to auth request to registry: {}", name);
    RegistryService registry = registryRepository.getByName(name);
    if (registry == null) {
        log.debug("auth : none due to unknown registry \"{}\"", name);
        return;
    }
    RegistryCredentials credentials = registry.getCredentials();
    if (credentials == null || !StringUtils.hasText(credentials.getPassword())) {
        log.debug("auth : none due to unknown registry \"{}\"", name);
        return;
    }
    String result = format("'{'\"username\":\"{0}\",\"password\":\"{1}\",\"email\":\"[email protected]\",\"serveraddress\":\"{2}\",\"auth\":\"\"'}'",
            credentials.getUsername(), credentials.getPassword(), url);
    log.debug("auth : {}", result);
    String xRegistryAuth = new String(Base64.encode(result.getBytes()));
    log.debug("X-Registry-Auth : [{}]", xRegistryAuth);
    headers.add("X-Registry-Auth", xRegistryAuth);
}
 
@Override
public ListenableFuture<ClientHttpResponse> intercept(final HttpRequest request,
		final byte[] body, final AsyncClientHttpRequestExecution execution)
		throws IOException {
	final URI originalUri = request.getURI();
	String serviceName = originalUri.getHost();
	return this.loadBalancer.execute(serviceName,
			new LoadBalancerRequest<ListenableFuture<ClientHttpResponse>>() {
				@Override
				public ListenableFuture<ClientHttpResponse> apply(
						final ServiceInstance instance) throws Exception {
					HttpRequest serviceRequest = new ServiceRequestWrapper(request,
							instance, AsyncLoadBalancerInterceptor.this.loadBalancer);
					return execution.executeAsync(serviceRequest, body);
				}

			});
}
 
源代码6 项目: spring-analysis-note   文件: DefaultWebClient.java
@SuppressWarnings("unchecked")
private <T extends Publisher<?>> T insertCheckpoint(T result, HttpStatus status, HttpRequest request) {
	String httpMethod = request.getMethodValue();
	URI uri = request.getURI();
	String description = status + " from " + httpMethod + " " + uri + " [DefaultWebClient]";
	if (result instanceof Mono) {
		return (T) ((Mono<?>) result).checkpoint(description);
	}
	else if (result instanceof Flux) {
		return (T) ((Flux<?>) result).checkpoint(description);
	}
	else {
		return result;
	}
}
 
源代码7 项目: spring-analysis-note   文件: WebUtils.java
/**
 * 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()));
}
 
@Override
public ListenableFuture<ClientHttpResponse> intercept(HttpRequest httpRequest, byte[] body,
                                                      AsyncClientHttpRequestExecution execution)
        throws IOException {
    logger.debug("AsyncRestTemplateCircuitInterceptor start");
    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 = AsyncRestTemplateCircuitInterceptor.class.getMethod(
                    "doExecuteAsync",
                    AsyncClientHttpRequestExecution.class,
                    HttpRequest.class, byte[].class);
            Object[] args = {httpRequest, body};
            ListenableFuture<ClientHttpResponse> response =
                    (ListenableFuture<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 execution.executeAsync(httpRequest, body);
    }
}
 
@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);
    }
}
 
源代码10 项目: java-technology-stack   文件: WebUtils.java
/**
 * 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()));
}
 
@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);
//        }
    }
 
public MutableHttpServerRequest(HttpRequest httpRequest, byte[] body) {
	this.httpMethod = httpRequest.getMethod();
	this.uri = httpRequest.getURI();
	this.path = uri.getPath();
	this.httpHeaders = httpRequest.getHeaders();
	this.queryParams = getParameters(httpRequest);
	this.httpInputMessage = new ByteArrayHttpInputMessage(body);
}
 
@Override
public ClientHttpResponse intercept(final HttpRequest request, final byte[] body,
		final ClientHttpRequestExecution execution) throws IOException {
	final URI originalUri = request.getURI();
	String serviceName = originalUri.getHost();
	Assert.state(serviceName != null,
			"Request URI does not contain a valid hostname: " + originalUri);
	return this.loadBalancer.execute(serviceName,
			this.requestFactory.createRequest(request, body, execution));
}
 
private static String initMessage(int status, String reasonPhrase, @Nullable HttpRequest request) {
	return status + " " + reasonPhrase +
			(request != null ? " from " + request.getMethodValue() + " " + request.getURI() : "");
}
 
private String getPath(HttpRequest request) {
	URI uri = request.getURI();
	return uri.getPath();
}
 
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
		ClientHttpRequestExecution execution) throws IOException {

	URI originalUri = request.getURI();

	String serviceName = originalUri.getHost();

	RequestMetadata clientMetadata = buildRequestMetadata(request);

	DubboRestServiceMetadata metadata = repository.get(serviceName, clientMetadata);

	if (metadata == null) {
		// if DubboServiceMetadata is not found, executes next
		return execution.execute(request, body);
	}

	RestMethodMetadata dubboRestMethodMetadata = metadata.getRestMethodMetadata();

	GenericService genericService = serviceFactory.create(metadata,
			dubboTranslatedAttributes);

	MutableHttpServerRequest httpServerRequest = new MutableHttpServerRequest(request,
			body);

	customizeRequest(httpServerRequest, dubboRestMethodMetadata, clientMetadata);

	DubboGenericServiceExecutionContext context = contextFactory
			.create(dubboRestMethodMetadata, httpServerRequest);

	Object result = null;
	GenericException exception = null;

	try {
		result = genericService.$invoke(context.getMethodName(),
				context.getParameterTypes(), context.getParameters());
	}
	catch (GenericException e) {
		exception = e;
	}

	return clientHttpResponseFactory.build(result, exception, clientMetadata,
			dubboRestMethodMetadata);
}
 
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
		ClientHttpRequestExecution execution) throws IOException {
	URI uri = request.getURI();
	String hostResource = request.getMethod().toString() + ":" + uri.getScheme()
			+ "://" + uri.getHost()
			+ (uri.getPort() == -1 ? "" : ":" + uri.getPort());
	String hostWithPathResource = hostResource + uri.getPath();
	boolean entryWithPath = true;
	if (hostResource.equals(hostWithPathResource)) {
		entryWithPath = false;
	}
	Method urlCleanerMethod = BlockClassRegistry.lookupUrlCleaner(
			sentinelRestTemplate.urlCleanerClass(),
			sentinelRestTemplate.urlCleaner());
	if (urlCleanerMethod != null) {
		hostWithPathResource = (String) methodInvoke(urlCleanerMethod,
				hostWithPathResource);
	}

	Entry hostEntry = null;
	Entry hostWithPathEntry = null;
	ClientHttpResponse response = null;
	try {
		hostEntry = SphU.entry(hostResource, EntryType.OUT);
		if (entryWithPath) {
			hostWithPathEntry = SphU.entry(hostWithPathResource, EntryType.OUT);
		}
		response = execution.execute(request, body);
		if (this.restTemplate.getErrorHandler().hasError(response)) {
			Tracer.trace(
					new IllegalStateException("RestTemplate ErrorHandler has error"));
		}
	}
	catch (Throwable e) {
		if (!BlockException.isBlockException(e)) {
			Tracer.trace(e);
		}
		else {
			return handleBlockException(request, body, execution, (BlockException) e);
		}
	}
	finally {
		if (hostWithPathEntry != null) {
			hostWithPathEntry.exit();
		}
		if (hostEntry != null) {
			hostEntry.exit();
		}
	}
	return response;
}
 
/**
 * Create a new {@code UriComponents} object from the URI associated 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) {
	URI uri = request.getURI();
	UriComponentsBuilder builder = UriComponentsBuilder.fromUri(uri);

	String scheme = uri.getScheme();
	String host = uri.getHost();
	int port = uri.getPort();

	String forwardedHeader = request.getHeaders().getFirst("Forwarded");
	if (StringUtils.hasText(forwardedHeader)) {
		String forwardedToUse = StringUtils.commaDelimitedListToStringArray(forwardedHeader)[0];
		Matcher m = FORWARDED_HOST_PATTERN.matcher(forwardedToUse);
		if (m.find()) {
			host = m.group(1).trim();
		}
		m = FORWARDED_PROTO_PATTERN.matcher(forwardedToUse);
		if (m.find()) {
			scheme = m.group(1).trim();
		}
	}
	else {
		String hostHeader = request.getHeaders().getFirst("X-Forwarded-Host");
		if (StringUtils.hasText(hostHeader)) {
			String[] hosts = StringUtils.commaDelimitedListToStringArray(hostHeader);
			String hostToUse = hosts[0];
			if (hostToUse.contains(":")) {
				String[] hostAndPort = StringUtils.split(hostToUse, ":");
				host = hostAndPort[0];
				port = Integer.parseInt(hostAndPort[1]);
			}
			else {
				host = hostToUse;
				port = -1;
			}
		}

		String portHeader = request.getHeaders().getFirst("X-Forwarded-Port");
		if (StringUtils.hasText(portHeader)) {
			String[] ports = StringUtils.commaDelimitedListToStringArray(portHeader);
			port = Integer.parseInt(ports[0]);
		}

		String protocolHeader = request.getHeaders().getFirst("X-Forwarded-Proto");
		if (StringUtils.hasText(protocolHeader)) {
			String[] protocols = StringUtils.commaDelimitedListToStringArray(protocolHeader);
			scheme = protocols[0];
		}
	}

	builder.scheme(scheme);
	builder.host(host);
	builder.port(null);
	if (scheme.equals("http") && port != 80 || scheme.equals("https") && port != 443) {
		builder.port(port);
	}
	return builder;
}
 
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
		ClientHttpRequestExecution execution) throws IOException {

	URI originalUri = request.getURI();

	String serviceName = originalUri.getHost();

	repository.initializeMetadata(serviceName);

	// Execute next
	return execution.execute(request, body);
}
 
源代码20 项目: spring-cloud-alibaba   文件: HttpUtils.java
/**
 * Get Parameters from the specified {@link HttpRequest request}.
 * @param request the specified {@link HttpRequest request}
 * @return map of parameters
 */
public static MultiValueMap<String, String> getParameters(HttpRequest request) {
	URI uri = request.getURI();
	return getParameters(uri.getQuery());
}