org.apache.http.HttpRequest类的使用及代码示例

x33g5p2x  于2022-01-19 转载在 其他  
字(12.3k)|赞(0)|评价(0)|浏览(567)

本文整理了Java中org.apache.http.HttpRequest类的一些代码示例,展示了HttpRequest类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。HttpRequest类的具体详情如下:
包路径:org.apache.http.HttpRequest
类名称:HttpRequest

HttpRequest介绍

[英]An HTTP request.
[中]HTTP请求。

代码示例

代码示例来源:origin: rest-assured/rest-assured

public void process(HttpRequest request, HttpContext ctx) throws HttpException, IOException {
  try {
    HttpHost host = (HttpHost) ctx.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    final URI requestURI = new URI(host.toURI()).resolve(request.getRequestLine().getUri());
    Verb verb = Verb.valueOf(request.getRequestLine().getMethod().toUpperCase());
    OAuthRequest oauthRequest = new OAuthRequest(verb, requestURI.toString(), null);
    this.service = (OAuth10aService) getOauthService(isOAuth1, addEmptyTokenToBaseString);
        request.setHeader(entry.getKey(), entry.getValue());

代码示例来源:origin: robovm/robovm

throw new IllegalArgumentException("HTTP context may not be null");
if (!request.containsHeader(HTTP.TARGET_HOST)) {
  HttpHost targethost = (HttpHost) context
    .getAttribute(ExecutionContext.HTTP_TARGET_HOST);
  if (targethost == null) {
    HttpConnection conn = (HttpConnection) context
      .getAttribute(ExecutionContext.HTTP_CONNECTION);
    if (conn instanceof HttpInetConnection) {
      int port = ((HttpInetConnection) conn).getRemotePort();
      if (address != null) {
        targethost = new HttpHost(address.getHostName(), port);
      ProtocolVersion ver = request.getRequestLine().getProtocolVersion();
      if (ver.lessEquals(HttpVersion.HTTP_1_0)) {
        return;
  request.addHeader(HTTP.TARGET_HOST, targethost.toHostString());

代码示例来源:origin: robolectric/robolectric

@Override
public boolean matches(HttpRequest request) {
 URI uri = URI.create(request.getRequestLine().getUri());
 if (method != null && !method.equals(request.getRequestLine().getMethod())) {
  return false;
 if (hostname != null && !hostname.equals(uri.getHost())) {
  return false;
 if (path != null && !path.equals(uri.getRawPath())) {
  return false;
  for (Header header : request.getAllHeaders()) {
   actualRequestHeaders.put(header.getName(), header.getValue());

代码示例来源:origin: code4craft/webmagic

public void process(
      final HttpRequest request,
      final HttpContext context) throws HttpException, IOException {
    if (!request.containsHeader("Accept-Encoding")) {
      request.addHeader("Accept-Encoding", "gzip");
    }
  }
});

代码示例来源:origin: robovm/robovm

public void process(final HttpRequest request, final HttpContext context) 
  throws HttpException, IOException {
  if (request == null) {
    throw new IllegalArgumentException("HTTP request may not be null");
  }
  if (!request.containsHeader(HTTP.USER_AGENT)) {
    String useragent = HttpProtocolParams.getUserAgent(request.getParams());
    if (useragent != null) {
      request.addHeader(HTTP.USER_AGENT, useragent);
    }
  }
}

代码示例来源:origin: robovm/robovm

public void process(final HttpRequest request, final HttpContext context) 
    throws HttpException, IOException {
  if (request == null) {
    throw new IllegalArgumentException
      ("HTTP request may not be null.");
  }
  if ((request instanceof HttpEntityEnclosingRequest) &&
    !request.containsHeader(HTTP.DATE_HEADER)) {
    String httpdate = DATE_GENERATOR.getCurrentDate();
    request.setHeader(HTTP.DATE_HEADER, httpdate); 
  }
}

代码示例来源:origin: robovm/robovm

Header locationHeader = response.getFirstHeader("location");
if (locationHeader == null) {
      "Received redirect response " + response.getStatusLine()
      + " but no location header");
  uri = new URI(location);            
} catch (URISyntaxException ex) {
  throw new ProtocolException("Invalid redirect URI: " + location, ex);
HttpParams params = response.getParams();
if (!uri.isAbsolute()) {
  if (params.isParameterTrue(ClientPNames.REJECT_RELATIVE_REDIRECT)) {
    throw new ProtocolException("Relative redirect location '" 
  HttpRequest request = (HttpRequest) context.getAttribute(
      ExecutionContext.HTTP_REQUEST);
    URI requestURI = new URI(request.getRequestLine().getUri());
    URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, true);
    uri = URIUtils.resolve(absoluteRequestURI, uri); 
  RedirectLocations redirectLocations = (RedirectLocations) context.getAttribute(
      REDIRECT_LOCATIONS);

代码示例来源:origin: org.codehaus.groovy.modules.http-builder/http-builder

public void sendRequestHeader(HttpRequest request)
  throws HttpException, IOException {
  try {
   HttpHost host = route.getTargetHost();

   URI uri = new URI(host.getSchemeName()
      + "://"
      + host.getHostName()
      + ((host.getPort() == -1) ? "" : (":" + host.getPort()))
      + request.getRequestLine().getUri());

   this.request = new HTTPRequest(uri.toURL(),
           HTTPMethod.valueOf(request.getRequestLine().getMethod()),
           FetchOptions.Builder.disallowTruncate().doNotFollowRedirects());
  }
  catch (URISyntaxException ex) {
   throw new IOException("Malformed request URI: " + ex.getMessage(), ex);
  }
  catch (IllegalArgumentException ex) {
   throw new IOException("Unsupported HTTP method: " + ex.getMessage(), ex);
  }

//     System.err.println("SEND: " + this.request.getMethod() + " " + this.request.getURL());

  for (Header h : request.getAllHeaders()) {
//       System.err.println("SEND: " + h.getName() + ": " + h.getValue());
   this.request.addHeader(new HTTPHeader(h.getName(), h.getValue()));
  }
 }

代码示例来源:origin: com.amazonaws/aws-xray-recorder-sdk-apache-http

public static String getUrl(HttpHost target, HttpRequest request) {
  String uri = request.getRequestLine().getUri();
  try {
    URI requestURI = new URI(uri);
    if (requestURI.isAbsolute()) {
      return requestURI.toString();
    }
  } catch (URISyntaxException ex){
    // Not a valid URI
  }
  return target.toURI() + uri;
}

代码示例来源:origin: robovm/robovm

CookieStore cookieStore = (CookieStore) context.getAttribute(
    ClientContext.COOKIE_STORE);
if (cookieStore == null) {
CookieSpecRegistry registry= (CookieSpecRegistry) context.getAttribute(
    ClientContext.COOKIESPEC_REGISTRY);
if (registry == null) {
String policy = HttpClientParams.getCookiePolicy(request.getParams());
if (this.log.isDebugEnabled()) {
  this.log.debug("CookieSpec selected: " + policy);
} else {
  try {
    requestURI = new URI(request.getRequestLine().getUri());
  } catch (URISyntaxException ex) {
    throw new ProtocolException("Invalid request URI: " + 
        request.getRequestLine().getUri(), ex);
CookieSpec cookieSpec = registry.getCookieSpec(policy, request.getParams());
  List<Header> headers = cookieSpec.formatCookies(matchedCookies);
  for (Header header : headers) {
    request.addHeader(header);
    if (header != null) {
      request.addHeader(header);

代码示例来源:origin: Impetus/Kundera

public void process(final HttpRequest request, final HttpContext context) throws IOException
  {
    if (logger.isInfoEnabled())
    {
      RequestLine requestLine = request.getRequestLine();
      logger.info(">> " + requestLine.getMethod() + " " + URI.create(requestLine.getUri()).getPath());
    }
  }
});

代码示例来源:origin: robolectric/robolectric

HttpHost newTarget = new HttpHost(
  uri.getHost(),
  uri.getPort(),
  uri.getScheme());
if (!route.getTargetHost().equals(newTarget)) {
 targetAuthState.invalidate();
 AuthScheme authScheme = proxyAuthState.getAuthScheme();
redirect.setHeaders(orig.getAllHeaders());
context.getAttribute(ClientContext.CREDS_PROVIDER);
  context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
 if (target == null) {
  target = route.getTargetHost();
 HttpHost proxy = route.getProxyHost();

代码示例来源:origin: robovm/robovm

/**
 * Decide whether a response comes with an entity.
 * The implementation in this class is based on RFC 2616.
 * Unknown methods and response codes are supposed to
 * indicate responses with an entity.
 * <br/>
 * Derived executors can override this method to handle
 * methods and response codes not specified in RFC 2616.
 *
 * @param request   the request, to obtain the executed method
 * @param response  the response, to obtain the status code
 */
protected boolean canResponseHaveBody(final HttpRequest request,
                   final HttpResponse response) {
  if ("HEAD".equalsIgnoreCase(request.getRequestLine().getMethod())) {
    return false;
  }
  int status = response.getStatusLine().getStatusCode(); 
  return status >= HttpStatus.SC_OK 
    && status != HttpStatus.SC_NO_CONTENT 
    && status != HttpStatus.SC_NOT_MODIFIED
    && status != HttpStatus.SC_RESET_CONTENT; 
}

代码示例来源:origin: robovm/robovm

public RequestWrapper(final HttpRequest request) throws ProtocolException {
  super();
  if (request == null) {
    throw new IllegalArgumentException("HTTP request may not be null");
  }
  this.original = request;
  setParams(request.getParams());
  // Make a copy of the original URI 
  if (request instanceof HttpUriRequest) {
    this.uri = ((HttpUriRequest) request).getURI();
    this.method = ((HttpUriRequest) request).getMethod();
    this.version = null;
  } else {
    RequestLine requestLine = request.getRequestLine();
    try {
      this.uri = new URI(requestLine.getUri());
    } catch (URISyntaxException ex) {
      throw new ProtocolException("Invalid request URI: " 
          + requestLine.getUri(), ex);
    }
    this.method = requestLine.getMethod();
    this.version = request.getProtocolVersion();
  }
  this.execCount = 0;
}

代码示例来源:origin: apache/cloudstack

final HttpServerConnection connObj = (HttpServerConnection)context.getAttribute("http.connection");
if (connObj instanceof SocketHttpServerConnection) {
  final InetAddress remoteAddr = ((SocketHttpServerConnection)connObj).getRemoteAddress();
  sb.append(remoteAddr.toString() + " -- ");
sb.append(StringUtils.cleanString(request.getRequestLine().toString()));
    paramList = URLEncodedUtils.parse(new URI(request.getRequestLine().getUri()), HttpUtils.UTF_8);
  } catch (final URISyntaxException e) {
    s_logger.error("Error parsing url request", e);
  parameterMap.put("httpmethod", new String[] {request.getRequestLine().getMethod()});

代码示例来源:origin: kingthy/TVRemoteIME

throws HttpException, IOException {
log.fine("Processing HTTP request: " + httpRequest.getRequestLine().toString());
String requestMethod = httpRequest.getRequestLine().getMethod();
String requestURI = httpRequest.getRequestLine().getUri();
    new StreamRequestMessage(
        UpnpRequest.Method.getByHttpName(requestMethod),
        URI.create(requestURI)
    );
} catch(IllegalArgumentException e) {
int requestHttpMinorVersion = httpRequest.getProtocolVersion().getMinor();
requestMessage.getOperation().setHttpMinorVersion(requestHttpMinorVersion);
  httpResponse.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
  httpResponse.setStatusLine(
      new BasicStatusLine(
          new ProtocolVersion("HTTP", 1, responseMsg.getOperation().getHttpMinorVersion()),
  log.fine("Response status line: " + httpResponse.getStatusLine());

代码示例来源:origin: Graylog2/graylog2-server

@Override
  public void process(HttpResponse response, HttpContext context) throws HttpException, IOException {
    // Avoid work if TRACE is not enabled for this class
    if (logger.isTraceEnabled()) {
      final StatusLine statusLine = response.getStatusLine();
      final HttpHost targetHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
      final HttpRequest httpRequest = (HttpRequest) context
          .getAttribute(HttpCoreContext.HTTP_REQUEST);
      final RequestLine request = httpRequest.getRequestLine();
      logger.trace("[{} {}]: {} {}{}",
          statusLine.getStatusCode(),
          statusLine.getReasonPhrase(),
          request.getMethod(),
          targetHost.toURI(),
          request.getUri()
      );
    }
  }
}

代码示例来源:origin: robovm/robovm

int status = response.getStatusLine().getStatusCode();
if (status == HttpStatus.SC_BAD_REQUEST ||
    status == HttpStatus.SC_REQUEST_TIMEOUT ||
    status == HttpStatus.SC_SERVICE_UNAVAILABLE ||
    status == HttpStatus.SC_NOT_IMPLEMENTED) {
  response.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
  return;
HttpEntity entity = response.getEntity();
if (entity != null) {
  ProtocolVersion ver = response.getStatusLine().getProtocolVersion();
  if (entity.getContentLength() < 0 && 
      (!entity.isChunked() || ver.lessEquals(HttpVersion.HTTP_1_0))) {
  context.getAttribute(ExecutionContext.HTTP_REQUEST);
if (request != null) {
  Header header = request.getFirstHeader(HTTP.CONN_DIRECTIVE);
  if (header != null) {
    response.setHeader(HTTP.CONN_DIRECTIVE, header.getValue());

代码示例来源:origin: robovm/robovm

throws HttpException, IOException {
HttpHost proxy = route.getProxyHost();
HttpHost target = route.getTargetHost();
HttpResponse response = null;
    connect.addHeader(HTTP.USER_AGENT, agent);
  connect.addHeader(HTTP.TARGET_HOST, target.toHostString());
    if (authScope != null || !authScheme.isConnectionBased()) {
      try {
        connect.addHeader(authScheme.authenticate(creds, connect));
      } catch (AuthenticationException ex) {
        if (this.log.isErrorEnabled()) {
    context.getAttribute(ClientContext.CREDS_PROVIDER);
          this.log.debug("Connection kept alive");
          HttpEntity entity = response.getEntity();
          if (entity != null) {
            entity.consumeContent();
int status = response.getStatusLine().getStatusCode();

代码示例来源:origin: org.apache.httpcomponents/com.springsource.org.apache.httpcomponents.httpclient-cache

private void ensurePartialContentIsNotSentToAClientThatDidNotRequestIt(HttpRequest request,
    HttpResponse response) throws IOException {
  if (request.getFirstHeader(HeaderConstants.RANGE) != null
      || response.getStatusLine().getStatusCode() != HttpStatus.SC_PARTIAL_CONTENT)
    return;
  consumeBody(response);
  throw new ClientProtocolException(UNEXPECTED_PARTIAL_CONTENT);
}

相关文章