當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。