当前位置: 首页>>代码示例>>Java>>正文


Java HttpResponse类代码示例

本文整理汇总了Java中org.jboss.netty.handler.codec.http.HttpResponse的典型用法代码示例。如果您正苦于以下问题:Java HttpResponse类的具体用法?Java HttpResponse怎么用?Java HttpResponse使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


HttpResponse类属于org.jboss.netty.handler.codec.http包,在下文中一共展示了HttpResponse类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: handleHandshake

import org.jboss.netty.handler.codec.http.HttpResponse; //导入依赖的package包/类
private void handleHandshake(ChannelHandlerContext ctx, HttpResponse response)
        throws Exception {
    this.dump(response);
    boolean validStatus = response.getStatus().equals(SUCCESS);
    boolean validUpgrade = (response.getHeader(Names.UPGRADE) != null)
            && response.getHeader(Names.UPGRADE).equalsIgnoreCase(Values.WEBSOCKET);
    boolean validConnection = (response.getHeader(Names.CONNECTION) != null)
            && response.getHeader(Names.CONNECTION).equalsIgnoreCase(Values.UPGRADE);

    if (!validStatus || !validUpgrade || !validConnection) {
        throw new LinkException(response.getStatus().getCode(),
                String.format(Text.WS_HANDSHAKE_INVALID, response.getContent().readable()
                        ? response.getContent().toString(Charset.forName("UTF-8")) : ""));
    }

    this.handshaker.finishHandshake(ctx.getChannel(), response);
    if (this.haveHandler()) {
        this.getHandler().onConnect(this.createContext(response));
    }
}
 
开发者ID:kuiwang,项目名称:my-dev,代码行数:21,代码来源:WebSocketClientUpstreamHandler.java

示例2: decode

import org.jboss.netty.handler.codec.http.HttpResponse; //导入依赖的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

示例3: setCorsResponseHeaders

import org.jboss.netty.handler.codec.http.HttpResponse; //导入依赖的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

示例4: setOrigin

import org.jboss.netty.handler.codec.http.HttpResponse; //导入依赖的package包/类
private boolean setOrigin(final HttpResponse response) {
    final String origin = request.headers().get(ORIGIN);
    if (!Strings.isNullOrEmpty(origin)) {
        if ("null".equals(origin) && config.isNullOriginAllowed()) {
            setAnyOrigin(response);
            return true;
        }
        if (config.isAnyOriginSupported()) {
            if (config.isCredentialsAllowed()) {
                echoRequestOrigin(response);
                setVaryHeader(response);
            } else {
                setAnyOrigin(response);
            }
            return true;
        }
        if (config.isOriginAllowed(origin)) {
            setOrigin(response, origin);
            setVaryHeader(response);
            return true;
        }
    }
    return false;
}
 
开发者ID:baidu,项目名称:Elasticsearch,代码行数:25,代码来源:CorsHandler.java

示例5: handle

import org.jboss.netty.handler.codec.http.HttpResponse; //导入依赖的package包/类
@Override
public void handle(Channel channel, Token<DelegationTokenIdentifier> token,
    String serviceUrl) throws IOException {
  Assert.assertEquals(testToken, token);

  Credentials creds = new Credentials();
  creds.addToken(new Text(serviceUrl), token);
  DataOutputBuffer out = new DataOutputBuffer();
  creds.write(out);
  int fileLength = out.getData().length;
  ChannelBuffer cbuffer = ChannelBuffers.buffer(fileLength);
  cbuffer.writeBytes(out.getData());
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
  response.setHeader(HttpHeaders.Names.CONTENT_LENGTH,
      String.valueOf(fileLength));
  response.setContent(cbuffer);
  channel.write(response).addListener(ChannelFutureListener.CLOSE);
}
 
开发者ID:naver,项目名称:hadoop,代码行数:19,代码来源:TestDelegationTokenRemoteFetcher.java

示例6: setResponseHeaders

import org.jboss.netty.handler.codec.http.HttpResponse; //导入依赖的package包/类
protected void setResponseHeaders(HttpResponse response,
    boolean keepAliveParam, long contentLength) {
  if (!connectionKeepAliveEnabled && !keepAliveParam) {
    if (LOG.isDebugEnabled()) {
      LOG.debug("Setting connection close header...");
    }
    response.setHeader(HttpHeaders.CONNECTION, CONNECTION_CLOSE);
  } else {
    response.setHeader(HttpHeaders.CONTENT_LENGTH,
      String.valueOf(contentLength));
    response.setHeader(HttpHeaders.CONNECTION, HttpHeaders.KEEP_ALIVE);
    response.setHeader(HttpHeaders.KEEP_ALIVE, "timeout="
        + connectionKeepAliveTimeOut);
    LOG.info("Content Length in shuffle : " + contentLength);
  }
}
 
开发者ID:aliyun-beta,项目名称:aliyun-oss-hadoop-fs,代码行数:17,代码来源:ShuffleHandler.java

示例7: messageReceived

import org.jboss.netty.handler.codec.http.HttpResponse; //导入依赖的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

示例8: doPost

import org.jboss.netty.handler.codec.http.HttpResponse; //导入依赖的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

示例9: writeRequested

import org.jboss.netty.handler.codec.http.HttpResponse; //导入依赖的package包/类
@Override
public void writeRequested(final ChannelHandlerContext ctx, final MessageEvent evt)
	throws Exception
{
	final HttpResponse resp = (HttpResponse)evt.getMessage();

	synchronized(this) {
		if (m_challenge != null) {
			try {
				/* Get appropriate response to challenge and
				 * add to the response base-64 encoded. XXX
				 */
				final String sig = Base64.encodePadded(getSignature());

				resp.setHeader(HeaderSignature, sig);
			}
			finally {
				/* Forget last challenge */
				m_challenge = null;
				m_localAddress = null;
			}
		}
	}

	super.writeRequested(ctx, evt);
}
 
开发者ID:SergioChan,项目名称:Android-Airplay-Server,代码行数:27,代码来源:RaopRtspChallengeResponseHandler.java

示例10: messageReceived

import org.jboss.netty.handler.codec.http.HttpResponse; //导入依赖的package包/类
@SuppressWarnings("unchecked")
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    HttpContext<R, T> httpContext = httpContextMap.get(ctx.getChannel());
    if (httpContext == null) {
        throw new IllegalStateException("no context for channel?");
    }
    try {
        if (e.getMessage() instanceof HttpResponse) {
            HttpResponse httpResponse = (HttpResponse) e.getMessage();
            HttpAction<R, T> action = httpContext.getHttpAction();
            ActionListener<T> listener = httpContext.getListener();
            httpContext.setHttpResponse(httpResponse);
            if (httpResponse.getContent().readable() && listener != null && action != null) {
                listener.onResponse(action.createResponse(httpContext));
            }
        }
    } finally {
        ctx.getChannel().close();
        httpContextMap.remove(ctx.getChannel());
    }
}
 
开发者ID:jprante,项目名称:elasticsearch-client-http,代码行数:23,代码来源:HttpClient.java

示例11: createResponse

import org.jboss.netty.handler.codec.http.HttpResponse; //导入依赖的package包/类
@Override
@SuppressWarnings("unchecked")
protected SearchResponse createResponse(HttpContext<SearchRequest, SearchResponse> httpContext) throws IOException {
    if (httpContext == null) {
        throw new IllegalStateException("no http context");
    }
    HttpResponse httpResponse = httpContext.getHttpResponse();
    logger.info("{}", httpResponse.getContent().toString(CharsetUtil.UTF_8));
    BytesReference ref = new ChannelBufferBytesReference(httpResponse.getContent());
    Map<String, Object> map = JsonXContent.jsonXContent.createParser(ref).map();

    logger.info("{}", map);

    InternalSearchResponse internalSearchResponse = parseInternalSearchResponse(map);
    String scrollId = (String) map.get(SCROLL_ID);
    int totalShards = 0;
    int successfulShards = 0;
    if (map.containsKey(SHARDS)) {
        Map<String, ?> shards = (Map<String, ?>) map.get(SHARDS);
        totalShards = shards.containsKey(TOTAL) ? (Integer) shards.get(TOTAL) : -1;
        successfulShards = shards.containsKey(SUCCESSFUL) ? (Integer) shards.get(SUCCESSFUL) : -1;
    }
    int tookInMillis = map.containsKey(TOOK) ? (Integer) map.get(TOOK) : -1;
    ShardSearchFailure[] shardFailures = null;
    return new SearchResponse(internalSearchResponse, scrollId, totalShards, successfulShards, tookInMillis, shardFailures);
}
 
开发者ID:jprante,项目名称:elasticsearch-client-http,代码行数:27,代码来源:HttpSearchAction.java

示例12: populateCamelHeaders

import org.jboss.netty.handler.codec.http.HttpResponse; //导入依赖的package包/类
@Override
public void populateCamelHeaders(HttpResponse response, Map<String, Object> headers, Exchange exchange, NettyHttpConfiguration configuration) throws Exception {
    LOG.trace("populateCamelHeaders: {}", response);

    headers.put(Exchange.HTTP_RESPONSE_CODE, response.getStatus().getCode());
    headers.put(Exchange.HTTP_RESPONSE_TEXT, response.getStatus().getReasonPhrase());

    for (String name : response.headers().names()) {
        // mapping the content-type
        if (name.toLowerCase().equals("content-type")) {
            name = Exchange.CONTENT_TYPE;
        }
        // add the headers one by one, and use the header filter strategy
        List<String> values = response.headers().getAll(name);
        Iterator<?> it = ObjectHelper.createIterator(values);
        while (it.hasNext()) {
            Object extracted = it.next();
            LOG.trace("HTTP-header: {}", extracted);
            if (headerFilterStrategy != null
                    && !headerFilterStrategy.applyFilterToExternalHeaders(name, extracted, exchange)) {
                NettyHttpHelper.appendHeader(headers, name, extracted);
            }
        }
    }
}
 
开发者ID:HydAu,项目名称:Camel,代码行数:26,代码来源:DefaultNettyHttpBinding.java

示例13: messageReceived

import org.jboss.netty.handler.codec.http.HttpResponse; //导入依赖的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

示例14: done

import org.jboss.netty.handler.codec.http.HttpResponse; //导入依赖的package包/类
@Override
public void done(boolean doneSync) {
    try {
        NettyHttpMessage nettyMessage = exchange.hasOut() ? exchange.getOut(NettyHttpMessage.class) : exchange.getIn(NettyHttpMessage.class);
        if (nettyMessage != null) {
            HttpResponse response = nettyMessage.getHttpResponse();
            if (response != null) {
                // the actual url is stored on the IN message in the getRequestBody method as its accessed on-demand
                String actualUrl = exchange.getIn().getHeader(Exchange.HTTP_URL, String.class);
                int code = response.getStatus() != null ? response.getStatus().getCode() : -1;
                log.debug("Http responseCode: {}", code);

                // if there was a http error code then check if we should throw an exception
                boolean ok = NettyHttpHelper.isStatusCodeOk(code, configuration.getOkStatusCodeRange());
                if (!ok && getConfiguration().isThrowExceptionOnFailure()) {
                    // operation failed so populate exception to throw
                    Exception cause = NettyHttpHelper.populateNettyHttpOperationFailedException(exchange, actualUrl, response, code, getConfiguration().isTransferException());
                    exchange.setException(cause);
                }
            }
        }
    } finally {
        // ensure we call the delegated callback
        callback.done(doneSync);
    }
}
 
开发者ID:HydAu,项目名称:Camel,代码行数:27,代码来源:NettyHttpProducer.java

示例15: convertToHttpResponse

import org.jboss.netty.handler.codec.http.HttpResponse; //导入依赖的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 convertToHttpResponse(Class<?> type, Exchange exchange, Object value, TypeConverterRegistry registry) {
    // if we want to covert to convertToHttpResponse
    if (value != null && HttpResponse.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) {
            return msg.getHttpResponse();
        }
    }

    return null;
}
 
开发者ID:HydAu,项目名称:Camel,代码行数:25,代码来源:NettyHttpConverter.java


注:本文中的org.jboss.netty.handler.codec.http.HttpResponse类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。