當前位置: 首頁>>代碼示例>>Java>>正文


Java HttpRequest類代碼示例

本文整理匯總了Java中org.jboss.netty.handler.codec.http.HttpRequest的典型用法代碼示例。如果您正苦於以下問題:Java HttpRequest類的具體用法?Java HttpRequest怎麽用?Java HttpRequest使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


HttpRequest類屬於org.jboss.netty.handler.codec.http包,在下文中一共展示了HttpRequest類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: decode

import org.jboss.netty.handler.codec.http.HttpRequest; //導入依賴的package包/類
@Override
protected Object decode(
        Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {

    HttpRequest request = (HttpRequest) msg;
    QueryStringDecoder decoder = new QueryStringDecoder(request.getUri());

    DeviceSession deviceSession = getDeviceSession(
            channel, remoteAddress, decoder.getParameters().get("UserName").get(0));
    if (deviceSession == null) {
        return null;
    }

    Parser parser = new Parser(PATTERN, decoder.getParameters().get("LOC").get(0));
    if (!parser.matches()) {
        return null;
    }

    Position position = new Position();
    position.setProtocol(getProtocolName());
    position.setDeviceId(deviceSession.getDeviceId());

    position.setTime(parser.nextDateTime(Parser.DateTimeFormat.DMY_HMS));

    position.setValid(true);
    position.setLatitude(parser.nextDouble(0));
    position.setLongitude(parser.nextDouble(0));
    position.setAltitude(parser.nextDouble(0));
    position.setSpeed(parser.nextDouble(0));
    position.setCourse(parser.nextDouble(0));

    if (channel != null) {
        HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
        channel.write(response).addListener(ChannelFutureListener.CLOSE);
    }

    return position;
}
 
開發者ID:bamartinezd,項目名稱:traccar-service,代碼行數:39,代碼來源:PathAwayProtocolDecoder.java

示例2: setCorsResponseHeaders

import org.jboss.netty.handler.codec.http.HttpRequest; //導入依賴的package包/類
public static void setCorsResponseHeaders(HttpRequest request, HttpResponse resp, CorsConfig config) {
    if (!config.isCorsSupportEnabled()) {
        return;
    }
    String originHeader = request.headers().get(ORIGIN);
    if (!Strings.isNullOrEmpty(originHeader)) {
        final String originHeaderVal;
        if (config.isAnyOriginSupported()) {
            originHeaderVal = ANY_ORIGIN;
        } else if (config.isOriginAllowed(originHeader) || isSameOrigin(originHeader, request.headers().get(HOST))) {
            originHeaderVal = originHeader;
        } else {
            originHeaderVal = null;
        }
        if (originHeaderVal != null) {
            resp.headers().add(ACCESS_CONTROL_ALLOW_ORIGIN, originHeaderVal);
        }
    }
    if (config.isCredentialsAllowed()) {
        resp.headers().add(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
    }
}
 
開發者ID:baidu,項目名稱:Elasticsearch,代碼行數:23,代碼來源:CorsHandler.java

示例3: messageReceived

import org.jboss.netty.handler.codec.http.HttpRequest; //導入依賴的package包/類
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
  try {
    final HttpRequest req = (HttpRequest) e.getMessage();
    if (req.getMethod().equals(HttpMethod.POST)) {
      doPost(ctx, e, req);
    } else if (req.getMethod().equals(HttpMethod.GET)) {
      doGet(ctx, e, req);
    } else {
      writeResponseAndClose(e, new DefaultHttpResponse(
              HttpVersion.HTTP_1_1,
              HttpResponseStatus.BAD_REQUEST));
    }
  } catch (Exception ex) {
    if (logger.isDebugEnabled())
      logger.debug("Failed to process message", ex);
    HttpResponse response = new DefaultHttpResponse(
            HttpVersion.HTTP_1_1,
            HttpResponseStatus.INTERNAL_SERVER_ERROR);
    response.setContent(
            ChannelBuffers.copiedBuffer(ex.getMessage().getBytes()));
    writeResponseAndClose(e, response);
  }
}
 
開發者ID:yandex,項目名稱:opentsdb-flume,代碼行數:25,代碼來源:LegacyHttpSource.java

示例4: doPost

import org.jboss.netty.handler.codec.http.HttpRequest; //導入依賴的package包/類
private void doPost(ChannelHandlerContext ctx, MessageEvent e, HttpRequest req)
        throws IOException {

  final QueryStringDecoder decoded = new QueryStringDecoder(req.getUri());
  if (!decoded.getPath().equalsIgnoreCase("/write")) {
    writeResponseAndClose(e,
            new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND));
    return;
  }

  try {
    metricParser.parse(req);
  } catch (IllegalArgumentException iae) {
    logger.warn("Metric parser failed: " + iae.getMessage());
  }

  HttpResponse response = new DefaultHttpResponse(
          HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
  response.setContent(ChannelBuffers.copiedBuffer(
          ("Seen events").getBytes()
  ));
  writeResponseAndClose(e, response);
}
 
開發者ID:yandex,項目名稱:opentsdb-flume,代碼行數:24,代碼來源:LegacyHttpSource.java

示例5: parse

import org.jboss.netty.handler.codec.http.HttpRequest; //導入依賴的package包/類
public void parse(HttpRequest req) throws IOException {

      final JsonParser parser = jsonFactory.createJsonParser(
              new ChannelBufferInputStream(req.getContent()));

      parser.nextToken(); // Skip the wrapper

      while (parser.nextToken() != JsonToken.END_OBJECT) {

        final String metric = parser.getCurrentName();

        JsonToken currentToken = parser.nextToken();
        if (currentToken == JsonToken.START_OBJECT) {
          parseMetricObject(metric, parser);
        } else if (currentToken == JsonToken.START_ARRAY) {
          int illegalTokens = parseMetricArray(metric, parser);
          if(illegalTokens > 0) {
              logger.warn("{} illegal tokens encountered", illegalTokens);
          }
        } else {
          logger.warn("Illegal token: expected {} or {}, but was {}: {}",new Object[] {
                  JsonToken.START_OBJECT, JsonToken.START_ARRAY, currentToken, parser.getText()});
        }
      }
    }
 
開發者ID:yandex,項目名稱:opentsdb-flume,代碼行數:26,代碼來源:LegacyHttpSource.java

示例6: toCamelMessage

import org.jboss.netty.handler.codec.http.HttpRequest; //導入依賴的package包/類
@Override
public Message toCamelMessage(HttpRequest request, Exchange exchange, NettyHttpConfiguration configuration) throws Exception {
    LOG.trace("toCamelMessage: {}", request);

    NettyHttpMessage answer = new NettyHttpMessage(request, null);
    answer.setExchange(exchange);
    if (configuration.isMapHeaders()) {
        populateCamelHeaders(request, answer.getHeaders(), exchange, configuration);
    }

    if (configuration.isDisableStreamCache()) {
        // keep the body as is, and use type converters
        answer.setBody(request.getContent());
    } else {
        // turn the body into stream cached
        NettyChannelBufferStreamCache cache = new NettyChannelBufferStreamCache(request.getContent());
        answer.setBody(cache);
    }
    return answer;
}
 
開發者ID:HydAu,項目名稱:Camel,代碼行數:21,代碼來源:DefaultNettyHttpBinding.java

示例7: createExchange

import org.jboss.netty.handler.codec.http.HttpRequest; //導入依賴的package包/類
@Override
public Exchange createExchange(ChannelHandlerContext ctx, MessageEvent messageEvent) throws Exception {
    Exchange exchange = createExchange();

    // use the http binding
    HttpRequest request = (HttpRequest) messageEvent.getMessage();
    Message in = getNettyHttpBinding().toCamelMessage(request, exchange, getConfiguration());
    exchange.setIn(in);
    
    // setup the common message headers 
    updateMessageHeader(in, ctx, messageEvent);

    // honor the character encoding
    String contentType = in.getHeader(Exchange.CONTENT_TYPE, String.class);
    String charset = NettyHttpHelper.getCharsetFromContentType(contentType);
    if (charset != null) {
        exchange.setProperty(Exchange.CHARSET_NAME, charset);
        in.setHeader(Exchange.HTTP_CHARACTER_ENCODING, charset);
    }

    return exchange;
}
 
開發者ID:HydAu,項目名稱:Camel,代碼行數:23,代碼來源:NettyHttpEndpoint.java

示例8: extractBasicAuthSubject

import org.jboss.netty.handler.codec.http.HttpRequest; //導入依賴的package包/類
/**
 * Extracts the username and password details from the HTTP basic header Authorization.
 * <p/>
 * This requires that the <tt>Authorization</tt> HTTP header is provided, and its using Basic.
 * Currently Digest is <b>not</b> supported.
 *
 * @return {@link HttpPrincipal} with username and password details, or <tt>null</tt> if not possible to extract
 */
protected static HttpPrincipal extractBasicAuthSubject(HttpRequest request) {
    String auth = request.headers().get("Authorization");
    if (auth != null) {
        String constraint = ObjectHelper.before(auth, " ");
        if (constraint != null) {
            if ("Basic".equalsIgnoreCase(constraint.trim())) {
                String decoded = ObjectHelper.after(auth, " ");
                // the decoded part is base64 encoded, so we need to decode that
                ChannelBuffer buf = ChannelBuffers.copiedBuffer(decoded.getBytes());
                ChannelBuffer out = Base64.decode(buf);
                String userAndPw = out.toString(Charset.defaultCharset());
                String username = ObjectHelper.before(userAndPw, ":");
                String password = ObjectHelper.after(userAndPw, ":");
                HttpPrincipal principal = new HttpPrincipal(username, password);

                LOG.debug("Extracted Basic Auth principal from HTTP header: {}", principal);
                return principal;
            }
        }
    }
    return null;
}
 
開發者ID:HydAu,項目名稱:Camel,代碼行數:31,代碼來源:HttpServerChannelHandler.java

示例9: messageReceived

import org.jboss.netty.handler.codec.http.HttpRequest; //導入依賴的package包/類
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent messageEvent) throws Exception {
    // store request, as this channel handler is created per pipeline
    HttpRequest request = (HttpRequest) messageEvent.getMessage();

    LOG.debug("Message received: {}", request);

    HttpServerChannelHandler handler = getHandler(request);
    if (handler != null) {
        // store handler as attachment
        ctx.setAttachment(handler);
        handler.messageReceived(ctx, messageEvent);
    } else {
        // this resource is not found, so send empty response back
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, NOT_FOUND);
        response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
        response.headers().set(Exchange.CONTENT_LENGTH, 0);
        response.setContent(ChannelBuffers.copiedBuffer(new byte[]{}));
        messageEvent.getChannel().write(response).syncUninterruptibly();
        // close the channel after send error message
        messageEvent.getChannel().close();
    }
}
 
開發者ID:HydAu,項目名稱:Camel,代碼行數:24,代碼來源:HttpServerMultiplexChannelHandler.java

示例10: getRequestBody

import org.jboss.netty.handler.codec.http.HttpRequest; //導入依賴的package包/類
@Override
protected Object getRequestBody(Exchange exchange) throws Exception {
    // creating the url to use takes 2-steps
    String uri = NettyHttpHelper.createURL(exchange, getEndpoint());
    URI u = NettyHttpHelper.createURI(exchange, uri, getEndpoint());

    HttpRequest request = getEndpoint().getNettyHttpBinding().toNettyRequest(exchange.getIn(), u.toString(), getConfiguration());
    String actualUri = request.getUri();
    exchange.getIn().setHeader(Exchange.HTTP_URL, actualUri);
    // Need to check if we need to close the connection or not
    if (!HttpHeaders.isKeepAlive(request)) {
        // just want to make sure we close the channel if the keepAlive is not true
        exchange.setProperty(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, true);
    }
    if (getConfiguration().isBridgeEndpoint()) {
        // Need to remove the Host key as it should be not used when bridging/proxying
        exchange.getIn().removeHeader("host");
    }

    return request;
}
 
開發者ID:HydAu,項目名稱:Camel,代碼行數:22,代碼來源:NettyHttpProducer.java

示例11: convertToHttpRequest

import org.jboss.netty.handler.codec.http.HttpRequest; //導入依賴的package包/類
/**
 * A fallback converter that allows us to easily call Java beans and use the raw Netty {@link HttpRequest} as parameter types.
 */
@FallbackConverter
public static Object convertToHttpRequest(Class<?> type, Exchange exchange, Object value, TypeConverterRegistry registry) {
    // if we want to covert to HttpRequest
    if (value != null && HttpRequest.class.isAssignableFrom(type)) {

        // okay we may need to cheat a bit when we want to grab the HttpRequest as its stored on the NettyHttpMessage
        // so if the message instance is a NettyHttpMessage and its body is the value, then we can grab the
        // HttpRequest from the NettyHttpMessage
        NettyHttpMessage msg;
        if (exchange.hasOut()) {
            msg = exchange.getOut(NettyHttpMessage.class);
        } else {
            msg = exchange.getIn(NettyHttpMessage.class);
        }
        if (msg != null && msg.getBody() == value) {
            // ensure the http request content is reset so we can read all the content out-of-the-box
            HttpRequest request = msg.getHttpRequest();
            request.getContent().resetReaderIndex();
            return request;
        }
    }

    return null;
}
 
開發者ID:HydAu,項目名稱:Camel,代碼行數:28,代碼來源:NettyHttpConverter.java

示例12: createRouteBuilder

import org.jboss.netty.handler.codec.http.HttpRequest; //導入依賴的package包/類
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("netty-http:http://0.0.0.0:{{port}}/foo")
                .to("mock:input")
                .process(new Processor() {
                    @Override
                    public void process(Exchange exchange) throws Exception {
                        // we can get the original http request
                        HttpRequest request = exchange.getIn(NettyHttpMessage.class).getHttpRequest();
                        assertNotNull(request);
                    }
                })
                .transform().constant("Bye World");
        }
    };
}
 
開發者ID:HydAu,項目名稱:Camel,代碼行數:20,代碼來源:NettyHttpAccessHttpRequestTest.java

示例13: VideoCache

import org.jboss.netty.handler.codec.http.HttpRequest; //導入依賴的package包/類
public VideoCache(ExecutorService pool, PropertyPlaceholder propsHolder, Service<HttpRequest, HttpResponse> client) {
    this.pool = pool;
    this.client = client;
    this.propsHolder = propsHolder;
    propsHolder.generatePropertyMap();
    
    this.productReader = new ProductFileReader(propsHolder.getPropertyMap().get("campaignProductListLocation"));
   
    JedisPoolConfig jedisConfig = new JedisPoolConfig();
    jedisConfig.setMaxTotal(Integer.parseInt(propsHolder.getPropertyMap().get("maxJedisPoolSize")));
    jedisConfig.setTestOnBorrow(true);
    jedisConfig.setLifo(false);
    String redisHost = propsHolder.getPropertyMap().get("redisServer");
    int redisPort = Integer.parseInt(propsHolder.getPropertyMap().get("redisPort"));
    this.jedisPool = new JedisPool(jedisConfig, redisHost, redisPort);
}
 
開發者ID:eternalthinker,項目名稱:finagle-java-example-master-slave,代碼行數:17,代碼來源:VideoCache.java

示例14: channelConnected

import org.jboss.netty.handler.codec.http.HttpRequest; //導入依賴的package包/類
@Override public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)
    throws Exception {
  HttpRequest request =
      new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.toString());
  request.addHeader(Names.ACCEPT, "text/event-stream");

  if (headers != null) {
    for (Map.Entry<String, String> entry : headers.entrySet()) {
      request.addHeader(entry.getKey(), entry.getValue());
    }
  }

  request.addHeader(Names.HOST, uri.getHost());
  request.addHeader(Names.ORIGIN, uri.getScheme() + "://" + uri.getHost());
  request.addHeader(Names.CACHE_CONTROL, "no-cache");
  if (lastEventId != null) {
    request.addHeader("Last-Event-ID", lastEventId);
  }
  e.getChannel().write(request);
  channel = e.getChannel();
}
 
開發者ID:tylerjroach,項目名稱:eventsource-android,代碼行數:22,代碼來源:EventSourceChannelHandler.java

示例15: handle

import org.jboss.netty.handler.codec.http.HttpRequest; //導入依賴的package包/類
@Override
public FileChunk [] handle(ChannelHandlerContext ctx, HttpRequest request)
    throws IOException {
  final String path = HttpDataServerHandler.sanitizeUri(request.getUri());
  if (path == null) {
    throw new IllegalArgumentException("Wrong path: " +path);
  }

  File file = new File(baseDir, path);
  if (file.isHidden() || !file.exists()) {
    throw new FileNotFoundException("No such file: " + baseDir + "/" + path);
  }
  if (!file.isFile()) {
    throw new FileAccessForbiddenException("No such file: " 
        + baseDir + "/" + path); 
  }
  
  return new FileChunk[] {new FileChunk(file, 0, file.length())};
}
 
開發者ID:apache,項目名稱:incubator-tajo,代碼行數:20,代碼來源:DirectoryRetriever.java


注:本文中的org.jboss.netty.handler.codec.http.HttpRequest類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。