org.apache.http.HttpEntityEnclosingRequest#getEntity ( )源码实例Demo

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

源代码1 项目: ArgusAPM   文件: AopHttpClient.java
private static HttpRequest handleRequest(HttpHost host, HttpRequest request, NetInfo data) {
    RequestLine requestLine = request.getRequestLine();
    if (requestLine != null) {
        String uri = requestLine.getUri();
        int i = (uri != null) && (uri.length() >= 10) && (uri.substring(0, 10).indexOf("://") >= 0) ? 1 : 0;
        if ((i == 0) && (uri != null) && (host != null)) {
            String uriFromHost = host.toURI().toString();
            data.setURL(uriFromHost + ((uriFromHost.endsWith("/")) || (uri.startsWith("/")) ? "" : "/") + uri);
        } else if (i != 0) {
            data.setURL(uri);
        }
    }
    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request;
        if (entityRequest.getEntity() != null) {
            entityRequest.setEntity(new AopHttpRequestEntity(entityRequest.getEntity(), data));
        }
        return entityRequest;
    }
    return request;
}
 
源代码2 项目: atlas   文件: Solr6Index.java
private void configureSolrClientsForKerberos() throws PermanentBackendException {
    String kerberosConfig = System.getProperty("java.security.auth.login.config");
    if(kerberosConfig == null) {
        throw new PermanentBackendException("Unable to configure kerberos for solr client. System property 'java.security.auth.login.config' is not set.");
    }
    logger.debug("Using kerberos configuration file located at '{}'.", kerberosConfig);
    try(Krb5HttpClientBuilder krbBuild = new Krb5HttpClientBuilder()) {

        SolrHttpClientBuilder kb = krbBuild.getBuilder();
        HttpClientUtil.setHttpClientBuilder(kb);
        HttpRequestInterceptor bufferedEntityInterceptor = new HttpRequestInterceptor() {
            @Override
            public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
                if(request instanceof HttpEntityEnclosingRequest) {
                    HttpEntityEnclosingRequest enclosingRequest = ((HttpEntityEnclosingRequest) request);
                    HttpEntity requestEntity = enclosingRequest.getEntity();
                    enclosingRequest.setEntity(new BufferedHttpEntity(requestEntity));
                }
            }
        };
        HttpClientUtil.addRequestInterceptor(bufferedEntityInterceptor);

        HttpRequestInterceptor preemptiveAuth = new PreemptiveAuth(new KerberosScheme());
        HttpClientUtil.addRequestInterceptor(preemptiveAuth);
    }
}
 
源代码3 项目: Repeat   文件: HttpServerUtilities.java
public static byte[] getPostContent(HttpRequest request) {
	if (!(request instanceof HttpEntityEnclosingRequest)) {
		LOGGER.warning("Unknown request type for POST request " + request.getClass());
		return null;
	}
	HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request;
	HttpEntity entity = entityRequest.getEntity();
	if (!(entity instanceof BasicHttpEntity)) {
		LOGGER.warning("Unknown entity type for POST request " + entity.getClass());
		return null;
	}
	BasicHttpEntity basicEntity = (BasicHttpEntity) entity;
	ByteArrayOutputStream buffer = new ByteArrayOutputStream();
	try {
		basicEntity.writeTo(buffer);
	} catch (IOException e) {
		LOGGER.log(Level.WARNING, "Failed to read all request content.", e);
		return null;
	}
	return buffer.toByteArray();
}
 
源代码4 项目: rest-client   文件: HTTPClientUtil.java
static String getHTTPRequestTrace(HttpRequest request) {
    StringBuilder sb = new StringBuilder();
    sb.append(request.getRequestLine());
    sb.append('\n');
    for (Header h : request.getAllHeaders()) {
        sb.append(h.getName()).append(": ").append(h.getValue()).append('\n');
    }
    sb.append('\n');

    // Check if the request is POST or PUT
    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntityEnclosingRequest r = (HttpEntityEnclosingRequest) request;
        HttpEntity e = r.getEntity();
        if (e != null) {
            appendHttpEntity(sb, e);
        }
    }
    return sb.toString();
}
 
private byte[] serializeContent(HttpRequest request) {
    if (!(request instanceof HttpEntityEnclosingRequest)) {
        return new byte[]{};
    }

    final HttpEntityEnclosingRequest entityWithRequest = (HttpEntityEnclosingRequest) request;
    HttpEntity entity = entityWithRequest.getEntity();
    if (entity == null) {
        return new byte[]{};
    }

    try {
        // Buffer non-repeatable entities
        if (!entity.isRepeatable()) {
            entityWithRequest.setEntity(new BufferedHttpEntity(entity));
        }
        return EntityUtils.toByteArray(entityWithRequest.getEntity());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
源代码6 项目: vividus   文件: HttpClientInterceptor.java
@Override
public void process(HttpRequest request, HttpContext context)
{
    byte[] body = null;
    String mimeType = null;
    if (request instanceof HttpEntityEnclosingRequest)
    {
        HttpEntityEnclosingRequest requestWithBody = (HttpEntityEnclosingRequest) request;
        HttpEntity entity = requestWithBody.getEntity();
        if (entity != null)
        {
            mimeType = Optional.ofNullable(ContentType.getLenient(entity))
                    .map(ContentType::getMimeType)
                    .orElseGet(() -> getMimeType(requestWithBody.getAllHeaders()));
            try (ByteArrayOutputStream baos = new ByteArrayOutputStream((int) entity.getContentLength()))
            {
                // https://github.com/apache/httpcomponents-client/commit/09cefc2b8970eea56d81b1a886d9bb769a48daf3
                entity.writeTo(baos);
                body = baos.toByteArray();
            }
            catch (IOException e)
            {
                LOGGER.error("Error is occurred at HTTP message parsing", e);
            }
        }
    }
    RequestLine requestLine = request.getRequestLine();
    String attachmentTitle = String.format("Request: %s %s", requestLine.getMethod(), requestLine.getUri());
    attachApiMessage(attachmentTitle, request.getAllHeaders(), body, mimeType, -1);
}
 
public void appendHttpClientRequestSpanTags(HttpRequest httpRequest,
                                            SofaTracerSpan httpClientSpan) {
    if (httpClientSpan == null) {
        return;
    }
    if (this.appName == null) {
        this.appName = SofaTracerConfiguration.getProperty(
            SofaTracerConfiguration.TRACER_APPNAME_KEY, StringUtils.EMPTY_STRING);
    }
    //lazy init
    RequestLine requestLine = httpRequest.getRequestLine();
    String methodName = requestLine.getMethod();
    //appName
    httpClientSpan.setTag(CommonSpanTags.LOCAL_APP,
        this.appName == null ? StringUtils.EMPTY_STRING : this.appName);
    //targetAppName
    httpClientSpan.setTag(CommonSpanTags.REMOTE_APP,
        this.targetAppName == null ? StringUtils.EMPTY_STRING : this.targetAppName);
    if (httpRequest instanceof HttpRequestWrapper) {
        HttpRequestWrapper httpRequestWrapper = (HttpRequestWrapper) httpRequest;
        httpClientSpan.setTag(CommonSpanTags.REQUEST_URL, httpRequestWrapper.getOriginal()
            .getRequestLine().getUri());
    } else {
        httpClientSpan.setTag(CommonSpanTags.REQUEST_URL, requestLine.getUri());
    }
    //method
    httpClientSpan.setTag(CommonSpanTags.METHOD, methodName);
    //length
    if (httpRequest instanceof HttpEntityEnclosingRequest) {
        HttpEntityEnclosingRequest httpEntityEnclosingRequest = (HttpEntityEnclosingRequest) httpRequest;
        HttpEntity httpEntity = httpEntityEnclosingRequest.getEntity();
        httpClientSpan.setTag(CommonSpanTags.REQ_SIZE,
            httpEntity == null ? -1 : httpEntity.getContentLength());
    }
    //carrier
    this.processHttpClientRequestCarrier(httpRequest, httpClientSpan);
}
 
源代码8 项目: ArgusAPM   文件: AopHttpClient.java
private static HttpUriRequest handleRequest(HttpUriRequest request, NetInfo data) {
    data.setURL(request.getURI().toString());
    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request;
        if (entityRequest.getEntity() != null) {
            entityRequest.setEntity(new AopHttpRequestEntity(entityRequest.getEntity(), data));
        }
        return (HttpUriRequest) entityRequest;
    }
    return request;
}
 
源代码9 项目: karate   文件: RequestLoggingInterceptor.java
@Override
public void process(org.apache.http.HttpRequest request, HttpContext httpContext) throws HttpException, IOException {
    HttpRequest actual = new HttpRequest();
    int id = counter.incrementAndGet();
    String uri = (String) httpContext.getAttribute(ApacheHttpClient.URI_CONTEXT_KEY);
    String method = request.getRequestLine().getMethod();
    actual.setUri(uri);
    actual.setMethod(method);        
    StringBuilder sb = new StringBuilder();
    sb.append("request:\n").append(id).append(" > ").append(method).append(' ').append(uri).append('\n');
    HttpLogModifier requestModifier = logModifier == null ? null : logModifier.enableForUri(uri) ? logModifier : null;
    LoggingUtils.logHeaders(requestModifier, sb, id, '>', request, actual);
    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request;
        HttpEntity entity = entityRequest.getEntity();
        if (LoggingUtils.isPrintable(entity)) {
            LoggingEntityWrapper wrapper = new LoggingEntityWrapper(entity); // todo optimize, preserve if stream
            String buffer = FileUtils.toString(wrapper.getContent());
            if (context.getConfig().isLogPrettyRequest()) {
                buffer = FileUtils.toPrettyString(buffer);
            }
            if (requestModifier != null) {
                buffer = requestModifier.request(uri, buffer);
            }
            sb.append(buffer).append('\n');
            actual.setBody(wrapper.getBytes());
            entityRequest.setEntity(wrapper);
        }
    }
    context.setPrevRequest(actual);
    context.logger.debug(sb.toString());
    actual.startTimer();
}
 
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
  if (request instanceof HttpEntityEnclosingRequest) {
    HttpEntityEnclosingRequest enclosingRequest = (HttpEntityEnclosingRequest) request;
    HttpEntity requestEntity = enclosingRequest.getEntity();
    enclosingRequest.setEntity(new BufferedHttpEntity(requestEntity));
  }
}
 
源代码11 项目: logbook   文件: LocalRequest.java
@Override
public State buffer(final HttpRequest request) throws IOException {
    if (request instanceof HttpEntityEnclosingRequest) {
        final HttpEntityEnclosingRequest original = (HttpEntityEnclosingRequest) request;
        if (original.getEntity() == null) {
            return new Passing();
        } else {
            final byte[] body = toByteArray(original.getEntity());
            original.setEntity(new ByteArrayEntity(body));
            return new Buffering(body);
        }
    } else {
        return new Passing();
    }
}
 
@Override
public void process(HttpRequest request, HttpContext context) throws HttpException,
    IOException {
  if(request instanceof HttpEntityEnclosingRequest) {
    HttpEntityEnclosingRequest enclosingRequest = ((HttpEntityEnclosingRequest) request);
    HttpEntity requestEntity = enclosingRequest.getEntity();
    enclosingRequest.setEntity(new BufferedHttpEntity(requestEntity));
  }
}
 
源代码13 项目: pinpoint   文件: HttpClient4EntityExtractor.java
@Override
public String getEntity(HttpRequest httpRequest) {
    if (httpRequest instanceof HttpEntityEnclosingRequest) {
        final HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) httpRequest;
        try {
            final HttpEntity entity = entityRequest.getEntity();
            if (entity != null && entity.isRepeatable() && entity.getContentLength() > 0) {
                return entityUtilsToString(entity, Charsets.UTF_8_NAME, 1024);
            }
        } catch (Exception e) {
            logger.debug("Failed to get entity. httpRequest={}", httpRequest, e);
        }
    }
    return null;
}
 
源代码14 项目: presto   文件: AwsRequestSigner.java
@Override
public void process(final HttpRequest request, final HttpContext context)
        throws IOException
{
    String method = request.getRequestLine().getMethod();

    URI uri = URI.create(request.getRequestLine().getUri());
    URIBuilder uriBuilder = new URIBuilder(uri);

    Map<String, List<String>> parameters = new TreeMap<>(CASE_INSENSITIVE_ORDER);
    for (NameValuePair parameter : uriBuilder.getQueryParams()) {
        parameters.computeIfAbsent(parameter.getName(), key -> new ArrayList<>())
                .add(parameter.getValue());
    }

    Map<String, String> headers = Arrays.stream(request.getAllHeaders())
            .collect(toImmutableMap(Header::getName, Header::getValue));

    InputStream content = null;
    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntityEnclosingRequest enclosingRequest = (HttpEntityEnclosingRequest) request;
        if (enclosingRequest.getEntity() != null) {
            content = enclosingRequest.getEntity().getContent();
        }
    }

    DefaultRequest<?> awsRequest = new DefaultRequest<>(SERVICE_NAME);

    HttpHost host = (HttpHost) context.getAttribute(HTTP_TARGET_HOST);
    if (host != null) {
        awsRequest.setEndpoint(URI.create(host.toURI()));
    }
    awsRequest.setHttpMethod(HttpMethodName.fromValue(method));
    awsRequest.setResourcePath(uri.getRawPath());
    awsRequest.setContent(content);
    awsRequest.setParameters(parameters);
    awsRequest.setHeaders(headers);

    signer.sign(awsRequest, credentialsProvider.getCredentials());

    Header[] newHeaders = awsRequest.getHeaders().entrySet().stream()
            .map(entry -> new BasicHeader(entry.getKey(), entry.getValue()))
            .toArray(Header[]::new);

    request.setHeaders(newHeaders);

    InputStream newContent = awsRequest.getContent();
    checkState(newContent == null || request instanceof HttpEntityEnclosingRequest);
    if (newContent != null) {
        BasicHttpEntity entity = new BasicHttpEntity();
        entity.setContent(newContent);
        ((HttpEntityEnclosingRequest) request).setEntity(entity);
    }
}
 
源代码15 项目: curl-logger   文件: Http2Curl.java
@SuppressWarnings("deprecation")
private CurlCommand http2curl(HttpRequest request)
    throws NoSuchFieldException, IllegalAccessException, IOException {

  Headers headers = new Headers(Arrays.asList(request.getAllHeaders()));
  CurlCommand curl = new CurlCommand();

  String inferredUri = inferUri(request);
  curl.setUrl(inferredUri);

  if (request instanceof HttpEntityEnclosingRequest) {
    HttpEntityEnclosingRequest requestWithEntity = (HttpEntityEnclosingRequest) request;
    try {
      HttpEntity entity = requestWithEntity.getEntity();
      if (entity != null) {
        Optional<String> maybeRequestContentType = tryGetHeaderValue(headers.toProcess,
            "Content-Type");
        String contentType = maybeRequestContentType
            .orElseThrow(() -> new IllegalStateException("Missing Content-Type header"));
        handleEntity(entity, contentType, headers, curl);
      }
    } catch (IOException e) {
      log.error("Failed to consume form data (entity) from HTTP request", e);
      throw e;
    }
  }

  String requestMethod = request.getRequestLine().getMethod();
  if ("GET".equals(requestMethod)) {
    // skip
  } else if ("POST".equals(requestMethod) && curl.hasData()) {
    // skip
  } else {
    curl.setMethod(requestMethod);
  }

  headers.toProcess = handleAuthenticationHeader(headers.toProcess, curl);

  List<Header> cookiesHeaders = headers.toProcess.stream()
      .filter(h -> h.getName().equals("Cookie"))
      .collect(Collectors.toList());
  if (cookiesHeaders.size() == 1) {
    curl.setCookieHeader(cookiesHeaders.get(0).getValue());
    headers.toProcess = headers.toProcess.stream().filter(h -> !h.getName().equals("Cookie"))
        .collect(Collectors.toList());
  } else if (cookiesHeaders.size() > 1) {
    // RFC 6265: When the user agent generates an HTTP request, the user agent MUST NOT attach
    // more than one Cookie header field.
    log.warn("More than one Cookie header in HTTP Request not allowed by RFC 6265");
  }

  handleNotIgnoredHeaders(headers, curl);

  curl.setCompressed(true);
  curl.setInsecure(true);
  curl.setVerbose(true);
  return curl;
}
 
源代码16 项目: travelguide   文件: AndroidHttpClient.java
/**
 * Generates a cURL command equivalent to the given request.
 */
private static String toCurl(HttpUriRequest request, boolean logAuthToken) throws IOException {
    StringBuilder builder = new StringBuilder();

    builder.append("curl ");

    for (Header header: request.getAllHeaders()) {
        if (!logAuthToken
                && (header.getName().equals("Authorization") ||
                    header.getName().equals("Cookie"))) {
            continue;
        }
        builder.append("--header \"");
        builder.append(header.toString().trim());
        builder.append("\" ");
    }

    URI uri = request.getURI();

    // If this is a wrapped request, use the URI from the original
    // request instead. getURI() on the wrapper seems to return a
    // relative URI. We want an absolute URI.
    if (request instanceof RequestWrapper) {
        HttpRequest original = ((RequestWrapper) request).getOriginal();
        if (original instanceof HttpUriRequest) {
            uri = ((HttpUriRequest) original).getURI();
        }
    }

    builder.append("\"");
    builder.append(uri);
    builder.append("\"");

    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntityEnclosingRequest entityRequest =
                (HttpEntityEnclosingRequest) request;
        HttpEntity entity = entityRequest.getEntity();
        if (entity != null && entity.isRepeatable()) {
            if (entity.getContentLength() < 1024) {
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                entity.writeTo(stream);
                String entityString = stream.toString();

                // TODO: Check the content type, too.
                builder.append(" --data-ascii \"")
                        .append(entityString)
                        .append("\"");
            } else {
                builder.append(" [TOO MUCH DATA TO INCLUDE]");
            }
        }
    }

    return builder.toString();
}
 
源代码17 项目: Alite   文件: AndroidHttpClient.java
/**
 * Generates a cURL command equivalent to the given request.
 */
private static String toCurl(HttpUriRequest request, boolean logAuthToken) throws IOException {
    StringBuilder builder = new StringBuilder();

    builder.append("curl ");

    for (Header header: request.getAllHeaders()) {
        if (!logAuthToken
                && (header.getName().equals("Authorization") ||
                    header.getName().equals("Cookie"))) {
            continue;
        }
        builder.append("--header \"");
        builder.append(header.toString().trim());
        builder.append("\" ");
    }

    URI uri = request.getURI();

    // If this is a wrapped request, use the URI from the original
    // request instead. getURI() on the wrapper seems to return a
    // relative URI. We want an absolute URI.
    if (request instanceof RequestWrapper) {
        HttpRequest original = ((RequestWrapper) request).getOriginal();
        if (original instanceof HttpUriRequest) {
            uri = ((HttpUriRequest) original).getURI();
        }
    }

    builder.append("\"");
    builder.append(uri);
    builder.append("\"");

    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntityEnclosingRequest entityRequest =
                (HttpEntityEnclosingRequest) request;
        HttpEntity entity = entityRequest.getEntity();
        if (entity != null && entity.isRepeatable()) {
            if (entity.getContentLength() < 1024) {
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                entity.writeTo(stream);
                String entityString = stream.toString();

                // TODO: Check the content type, too.
                builder.append(" --data-ascii \"")
                        .append(entityString)
                        .append("\"");
            } else {
                builder.append(" [TOO MUCH DATA TO INCLUDE]");
            }
        }
    }

    return builder.toString();
}
 
/**
 * Generates a cURL command equivalent to the given request.
 */
private static String toCurl(HttpUriRequest request, boolean logAuthToken)
		throws IOException {
	StringBuilder builder = new StringBuilder();

	builder.append("curl ");

	for (Header header : request.getAllHeaders()) {
		if (!logAuthToken
				&& (header.getName().equals("Authorization") || header
						.getName().equals("Cookie"))) {
			continue;
		}
		builder.append("--header \"");
		builder.append(header.toString().trim());
		builder.append("\" ");
	}

	URI uri = request.getURI();

	// If this is a wrapped request, use the URI from the original
	// request instead. getURI() on the wrapper seems to return a
	// relative URI. We want an absolute URI.
	if (request instanceof RequestWrapper) {
		HttpRequest original = ((RequestWrapper) request).getOriginal();
		if (original instanceof HttpUriRequest) {
			uri = ((HttpUriRequest) original).getURI();
		}
	}

	builder.append("\"");
	builder.append(uri);
	builder.append("\"");

	if (request instanceof HttpEntityEnclosingRequest) {
		HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request;
		HttpEntity entity = entityRequest.getEntity();
		if (entity != null && entity.isRepeatable()) {
			if (entity.getContentLength() < 1024) {
				ByteArrayOutputStream stream = new ByteArrayOutputStream();
				entity.writeTo(stream);
				String entityString = stream.toString();

				// TODO: Check the content type, too.
				builder.append(" --data-ascii \"").append(entityString)
						.append("\"");
			} else {
				builder.append(" [TOO MUCH DATA TO INCLUDE]");
			}
		}
	}

	return builder.toString();
}
 
源代码19 项目: AndroidWebServ   文件: HttpServRequestContext.java
public HttpServRequestContext(HttpEntityEnclosingRequest request) {
    this.request = request;
    this.entity = request.getEntity();
}