Java Code Examples for io.netty.handler.codec.http.FullHttpResponse#headers()

The following examples show how to use io.netty.handler.codec.http.FullHttpResponse#headers() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WebSocketClientHandshaker08.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * Process server response:
 * </p>
 *
 * <pre>
 * HTTP/1.1 101 Switching Protocols
 * Upgrade: websocket
 * Connection: Upgrade
 * Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
 * Sec-WebSocket-Protocol: chat
 * </pre>
 *
 * @param response
 *            HTTP response returned from the server for the request sent by beginOpeningHandshake00().
 * @throws WebSocketHandshakeException
 */
@Override
protected void verify(FullHttpResponse response) {
    final HttpResponseStatus status = HttpResponseStatus.SWITCHING_PROTOCOLS;
    final HttpHeaders headers = response.headers();

    if (!response.getStatus().equals(status)) {
        throw new WebSocketHandshakeException("Invalid handshake response getStatus: " + response.getStatus());
    }

    String upgrade = headers.get(Names.UPGRADE);
    if (!Values.WEBSOCKET.equalsIgnoreCase(upgrade)) {
        throw new WebSocketHandshakeException("Invalid handshake response upgrade: " + upgrade);
    }

    String connection = headers.get(Names.CONNECTION);
    if (!Values.UPGRADE.equalsIgnoreCase(connection)) {
        throw new WebSocketHandshakeException("Invalid handshake response connection: " + connection);
    }

    String accept = headers.get(Names.SEC_WEBSOCKET_ACCEPT);
    if (accept == null || !accept.equals(expectedChallengeResponseString)) {
        throw new WebSocketHandshakeException(String.format(
                "Invalid challenge. Actual: %s. Expected: %s", accept, expectedChallengeResponseString));
    }
}
 
Example 2
Source File: WebSocketClientHandshaker07.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * Process server response:
 * </p>
 *
 * <pre>
 * HTTP/1.1 101 Switching Protocols
 * Upgrade: websocket
 * Connection: Upgrade
 * Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
 * Sec-WebSocket-Protocol: chat
 * </pre>
 *
 * @param response
 *            HTTP response returned from the server for the request sent by beginOpeningHandshake00().
 * @throws WebSocketHandshakeException
 */
@Override
protected void verify(FullHttpResponse response) {
    final HttpResponseStatus status = HttpResponseStatus.SWITCHING_PROTOCOLS;
    final HttpHeaders headers = response.headers();

    if (!response.getStatus().equals(status)) {
        throw new WebSocketHandshakeException("Invalid handshake response getStatus: " + response.getStatus());
    }

    String upgrade = headers.get(Names.UPGRADE);
    if (!Values.WEBSOCKET.equalsIgnoreCase(upgrade)) {
        throw new WebSocketHandshakeException("Invalid handshake response upgrade: " + upgrade);
    }

    String connection = headers.get(Names.CONNECTION);
    if (!Values.UPGRADE.equalsIgnoreCase(connection)) {
        throw new WebSocketHandshakeException("Invalid handshake response connection: " + connection);
    }

    String accept = headers.get(Names.SEC_WEBSOCKET_ACCEPT);
    if (accept == null || !accept.equals(expectedChallengeResponseString)) {
        throw new WebSocketHandshakeException(String.format(
                "Invalid challenge. Actual: %s. Expected: %s", accept, expectedChallengeResponseString));
    }
}
 
Example 3
Source File: WebSocketClientHandshaker13.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * Process server response:
 * </p>
 *
 * <pre>
 * HTTP/1.1 101 Switching Protocols
 * Upgrade: websocket
 * Connection: Upgrade
 * Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
 * Sec-WebSocket-Protocol: chat
 * </pre>
 *
 * @param response
 *            HTTP response returned from the server for the request sent by beginOpeningHandshake00().
 * @throws WebSocketHandshakeException
 */
@Override
protected void verify(FullHttpResponse response) {
    final HttpResponseStatus status = HttpResponseStatus.SWITCHING_PROTOCOLS;
    final HttpHeaders headers = response.headers();

    if (!response.getStatus().equals(status)) {
        throw new WebSocketHandshakeException("Invalid handshake response getStatus: " + response.getStatus());
    }

    String upgrade = headers.get(Names.UPGRADE);
    if (!Values.WEBSOCKET.equalsIgnoreCase(upgrade)) {
        throw new WebSocketHandshakeException("Invalid handshake response upgrade: " + upgrade);
    }

    String connection = headers.get(Names.CONNECTION);
    if (!Values.UPGRADE.equalsIgnoreCase(connection)) {
        throw new WebSocketHandshakeException("Invalid handshake response connection: " + connection);
    }

    String accept = headers.get(Names.SEC_WEBSOCKET_ACCEPT);
    if (accept == null || !accept.equals(expectedChallengeResponseString)) {
        throw new WebSocketHandshakeException(String.format(
                "Invalid challenge. Actual: %s. Expected: %s", accept, expectedChallengeResponseString));
    }
}
 
Example 4
Source File: WebSocketClientHandshaker13.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * Process server response:
 * </p>
 *
 * <pre>
 * HTTP/1.1 101 Switching Protocols
 * Upgrade: websocket
 * Connection: Upgrade
 * Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
 * Sec-WebSocket-Protocol: chat
 * </pre>
 *
 * @param response
 *            HTTP response returned from the server for the request sent by beginOpeningHandshake00().
 * @throws WebSocketHandshakeException
 */
@Override
protected void verify(FullHttpResponse response) {
    final HttpResponseStatus status = HttpResponseStatus.SWITCHING_PROTOCOLS;
    final HttpHeaders headers = response.headers();

    if (!response.status().equals(status)) {
        throw new WebSocketHandshakeException("Invalid handshake response getStatus: " + response.status());
    }

    CharSequence upgrade = headers.get(HttpHeaderNames.UPGRADE);
    if (!HttpHeaderValues.WEBSOCKET.contentEqualsIgnoreCase(upgrade)) {
        throw new WebSocketHandshakeException("Invalid handshake response upgrade: " + upgrade);
    }

    if (!headers.containsValue(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE, true)) {
        throw new WebSocketHandshakeException("Invalid handshake response connection: "
                + headers.get(HttpHeaderNames.CONNECTION));
    }

    CharSequence accept = headers.get(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT);
    if (accept == null || !accept.equals(expectedChallengeResponseString)) {
        throw new WebSocketHandshakeException(String.format(
                "Invalid challenge. Actual: %s. Expected: %s", accept, expectedChallengeResponseString));
    }
}
 
Example 5
Source File: WebSocketClientHandshaker07.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * Process server response:
 * </p>
 *
 * <pre>
 * HTTP/1.1 101 Switching Protocols
 * Upgrade: websocket
 * Connection: Upgrade
 * Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
 * Sec-WebSocket-Protocol: chat
 * </pre>
 *
 * @param response
 *            HTTP response returned from the server for the request sent by beginOpeningHandshake00().
 * @throws WebSocketHandshakeException
 */
@Override
protected void verify(FullHttpResponse response) {
    final HttpResponseStatus status = HttpResponseStatus.SWITCHING_PROTOCOLS;
    final HttpHeaders headers = response.headers();

    if (!response.status().equals(status)) {
        throw new WebSocketHandshakeException("Invalid handshake response getStatus: " + response.status());
    }

    CharSequence upgrade = headers.get(HttpHeaderNames.UPGRADE);
    if (!HttpHeaderValues.WEBSOCKET.contentEqualsIgnoreCase(upgrade)) {
        throw new WebSocketHandshakeException("Invalid handshake response upgrade: " + upgrade);
    }

    if (!headers.containsValue(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE, true)) {
        throw new WebSocketHandshakeException("Invalid handshake response connection: "
                + headers.get(HttpHeaderNames.CONNECTION));
    }

    CharSequence accept = headers.get(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT);
    if (accept == null || !accept.equals(expectedChallengeResponseString)) {
        throw new WebSocketHandshakeException(String.format(
                "Invalid challenge. Actual: %s. Expected: %s", accept, expectedChallengeResponseString));
    }
}
 
Example 6
Source File: WebSocketClientHandshaker08.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * Process server response:
 * </p>
 *
 * <pre>
 * HTTP/1.1 101 Switching Protocols
 * Upgrade: websocket
 * Connection: Upgrade
 * Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
 * Sec-WebSocket-Protocol: chat
 * </pre>
 *
 * @param response
 *            HTTP response returned from the server for the request sent by beginOpeningHandshake00().
 * @throws WebSocketHandshakeException
 */
@Override
protected void verify(FullHttpResponse response) {
    final HttpResponseStatus status = HttpResponseStatus.SWITCHING_PROTOCOLS;
    final HttpHeaders headers = response.headers();

    if (!response.status().equals(status)) {
        throw new WebSocketHandshakeException("Invalid handshake response getStatus: " + response.status());
    }

    CharSequence upgrade = headers.get(HttpHeaderNames.UPGRADE);
    if (!HttpHeaderValues.WEBSOCKET.contentEqualsIgnoreCase(upgrade)) {
        throw new WebSocketHandshakeException("Invalid handshake response upgrade: " + upgrade);
    }

    if (!headers.containsValue(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE, true)) {
        throw new WebSocketHandshakeException("Invalid handshake response connection: "
                + headers.get(HttpHeaderNames.CONNECTION));
    }

    CharSequence accept = headers.get(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT);
    if (accept == null || !accept.equals(expectedChallengeResponseString)) {
        throw new WebSocketHandshakeException(String.format(
                "Invalid challenge. Actual: %s. Expected: %s", accept, expectedChallengeResponseString));
    }
}
 
Example 7
Source File: WebSocketClientHandshaker00.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * Process server response:
 * </p>
 *
 * <pre>
 * HTTP/1.1 101 WebSocket Protocol Handshake
 * Upgrade: WebSocket
 * Connection: Upgrade
 * Sec-WebSocket-Origin: http://example.com
 * Sec-WebSocket-Location: ws://example.com/demo
 * Sec-WebSocket-Protocol: sample
 *
 * 8jKS'y:G*Co,Wxa-
 * </pre>
 *
 * @param response
 *            HTTP response returned from the server for the request sent by beginOpeningHandshake00().
 * @throws WebSocketHandshakeException
 */
@Override
protected void verify(FullHttpResponse response) {
    if (!response.status().equals(HttpResponseStatus.SWITCHING_PROTOCOLS)) {
        throw new WebSocketHandshakeException("Invalid handshake response getStatus: " + response.status());
    }

    HttpHeaders headers = response.headers();

    CharSequence upgrade = headers.get(HttpHeaderNames.UPGRADE);
    if (!WEBSOCKET.contentEqualsIgnoreCase(upgrade)) {
        throw new WebSocketHandshakeException("Invalid handshake response upgrade: "
                + upgrade);
    }

    if (!headers.containsValue(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE, true)) {
        throw new WebSocketHandshakeException("Invalid handshake response connection: "
                + headers.get(HttpHeaderNames.CONNECTION));
    }

    ByteBuf challenge = response.content();
    if (!challenge.equals(expectedChallengeResponseBytes)) {
        throw new WebSocketHandshakeException("Invalid challenge");
    }
}
 
Example 8
Source File: HelloServerHandler.java    From crow-benchmark with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void writeResponse(ChannelHandlerContext ctx, HttpRequest request, ByteBuf buf, CharSequence contentType, CharSequence contentLength) {
// Decide whether to close the connection or not.
boolean keepAlive = HttpHeaders.isKeepAlive(request);
// Build the response object.
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf, false);
HttpHeaders headers = response.headers();
headers.set(CONTENT_TYPE_ENTITY, contentType);
headers.set(SERVER_ENTITY, SERVER_NAME);
headers.set(DATE_ENTITY, date);
headers.set(CONTENT_LENGTH_ENTITY, contentLength);

// Close the non-keep-alive connection after the write operation is
// done.
if (!keepAlive) {
    ctx.write(response).addListener(ChannelFutureListener.CLOSE);
} else {
    ctx.write(response, ctx.voidPromise());
}
   }
 
Example 9
Source File: Http2ClientChannelHandler.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception {
    HttpHeaders headers = msg.headers();
    Integer streamId = headers.getInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text());
    if (streamId == null) {
        if (LOGGER.isWarnEnabled()) {
            LOGGER.warn("HttpResponseHandler unexpected message received: {}, data is {}", msg.toString(),
                NettyHelper.toString(msg.content()));
        }
        return;
    }

    Entry<ChannelFuture, AbstractHttpClientHandler> entry = removePromise(streamId);
    if (entry == null) {
        if (LOGGER.isWarnEnabled()) {
            LOGGER.warn("Message received for unknown stream id {}, msg is {}, data is {}", streamId,
                msg.toString(), NettyHelper.toString(msg.content()));
        }
    } else {
        final AbstractHttpClientHandler callback = entry.getValue();
        callback.receiveHttpResponse(msg);
    }
}
 
Example 10
Source File: Http1ServerTask.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
protected void sendHttp1Response0(HttpResponseStatus status, boolean error, ByteBuf content) {
    FullHttpResponse httpResponse = new DefaultFullHttpResponse(HTTP_1_1, status, content);
    HttpHeaders headers = httpResponse.headers();

    headers.setInt(CONTENT_LENGTH, httpResponse.content().readableBytes());
    if (request.getSerializeType() > 0) {
        String serialization = SerializerFactory.getAliasByCode(request.getSerializeType());
        headers.set(RemotingConstants.HEAD_SERIALIZE_TYPE, serialization);
    } else {
        headers.set(CONTENT_TYPE, "text/plain; charset=" + RpcConstants.DEFAULT_CHARSET.displayName());
    }
    if (error) {
        headers.set(RemotingConstants.HEAD_RESPONSE_ERROR, "true");
    }
    if (!keepAlive) {
        ctx.write(httpResponse).addListener(ChannelFutureListener.CLOSE);
    } else {
        httpResponse.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        ctx.write(httpResponse);
    }
}
 
Example 11
Source File: DFHttpSyncHandler.java    From dfactor with MIT License 5 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
	try{
		if(msg instanceof FullHttpResponse){
			FullHttpResponse rsp = (FullHttpResponse) msg;
			HttpHeaders headers = rsp.headers();
			long contentLen = HttpUtil.getContentLength(rsp);
			String contentType = headers.get(HttpHeaderNames.CONTENT_TYPE);
			//
			DFHttpCliRsp dfRsp = null;
			ByteBuf buf = rsp.content();
			//parse msg
			boolean isString = contentIsString(contentType);
			if(isString){  //String
				String str = null;
				if(buf != null){
					str = (String) buf.readCharSequence(buf.readableBytes(), CharsetUtil.UTF_8);
				}
				dfRsp = new DFHttpCliRspWrap(rsp.status().code(), headers,
						contentType, (int) contentLen, 
						null, str);
			}else{  //binary
				dfRsp = new DFHttpCliRspWrap(rsp.status().code(), headers,
						contentType, (int) contentLen, 
						buf, null);
			}
			//
			_recvData = dfRsp;
			if(!isString && buf != null){
       			buf.retain();
       		}
		}
	}finally{
		if(_recvPromise != null){
			_recvPromise.setSuccess();
		}
		ReferenceCountUtil.release(msg);
	}
}
 
Example 12
Source File: WebSocketClientHandshaker00.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * Process server response:
 * </p>
 *
 * <pre>
 * HTTP/1.1 101 WebSocket Protocol Handshake
 * Upgrade: WebSocket
 * Connection: Upgrade
 * Sec-WebSocket-Origin: http://example.com
 * Sec-WebSocket-Location: ws://example.com/demo
 * Sec-WebSocket-Protocol: sample
 *
 * 8jKS'y:G*Co,Wxa-
 * </pre>
 *
 * @param response
 *            HTTP response returned from the server for the request sent by beginOpeningHandshake00().
 * @throws WebSocketHandshakeException
 */
@Override
protected void verify(FullHttpResponse response) {
    final HttpResponseStatus status = new HttpResponseStatus(101, "WebSocket Protocol Handshake");

    if (!response.getStatus().equals(status)) {
        throw new WebSocketHandshakeException("Invalid handshake response getStatus: " + response.getStatus());
    }

    HttpHeaders headers = response.headers();

    String upgrade = headers.get(Names.UPGRADE);
    if (!Values.WEBSOCKET.equalsIgnoreCase(upgrade)) {
        throw new WebSocketHandshakeException("Invalid handshake response upgrade: "
                + upgrade);
    }

    String connection = headers.get(Names.CONNECTION);
    if (!Values.UPGRADE.equalsIgnoreCase(connection)) {
        throw new WebSocketHandshakeException("Invalid handshake response connection: "
                + connection);
    }

    ByteBuf challenge = response.content();
    if (!challenge.equals(expectedChallengeResponseBytes)) {
        throw new WebSocketHandshakeException("Invalid challenge");
    }
}
 
Example 13
Source File: ComponentTestUtils.java    From riposte with Apache License 2.0 5 votes vote down vote up
public NettyHttpClientResponse(FullHttpResponse fullHttpResponse) {
    this.statusCode = fullHttpResponse.status().code();
    this.headers = fullHttpResponse.headers();
    ByteBuf content = fullHttpResponse.content();
    this.payloadBytes = new byte[content.readableBytes()];
    content.getBytes(content.readerIndex(), this.payloadBytes);
    this.payload = new String(this.payloadBytes, UTF_8);
    this.fullHttpResponse = fullHttpResponse;
}
 
Example 14
Source File: LogUtil.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Print the headers associated with the initial Http Response.
 * The header details will be printed in the following format.
 * <p>
 * " >> Headers [channelContextId] [header name] : [header value]"
 *
 * @param log {@link Log} object of the relevant class
 * @param msg {@link FullHttpResponse} response from the backend
 * @param ctx {@link ChannelHandlerContext} context
 */
public static void printHeaders(Log log, FullHttpResponse msg, ChannelHandlerContext ctx) {
    //the direction is always inbound.
    String logStatement = getDirectionString(true) + "Headers " + resolveContextId(ctx) + " ";
    if (msg.headers() == null || msg.headers().isEmpty()) {
        log.debug(logStatement + "empty");
    } else {
        for (Map.Entry<String, String> entry : msg.headers().entries()) {
            log.debug(logStatement + entry.getKey() + ":" + entry.getValue());
        }
    }
}
 
Example 15
Source File: HttpProcessHandler.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
private static final FullHttpResponse http_500(String errorMessage) {
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR
            , Unpooled.wrappedBuffer(errorMessage.getBytes()));
    HttpHeaders httpHeaders = response.headers();
    httpHeaders.set(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
    httpHeaders.set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());
    return response;
}
 
Example 16
Source File: HttpProcessHandler.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
private static final FullHttpResponse http_404() {
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND);
    HttpHeaders httpHeaders = response.headers();
    httpHeaders.set(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
    httpHeaders.set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());
    return response;
}
 
Example 17
Source File: HTTPLogger.java    From ari4java with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void traceResponse(FullHttpResponse response, byte[] responseBytes) {
    if (logger.isTraceEnabled()) {
        StringBuilder data = new StringBuilder();
        data.append(response.protocolVersion());
        data.append(" ");
        data.append(response.status().toString());
        data.append("\n");
        for (Map.Entry<String, String> e: response.headers()) {
            data.append(e.getKey());
            data.append(": ");
            data.append(e.getValue());
            data.append("\n");
        }
        if (responseBytes != null) {
            data.append("\n");
            if ("audio/wav".equals(response.headers().get("Content-Type"))) {
                data.append("[binary data...]");
            } else {
                int len = responseBytes.length;
                if (len > maxLen) {
                    len = maxLen;
                }
                data.append(new String(Arrays.copyOf(responseBytes, len), ARIEncoder.ENCODING));
                if (responseBytes.length > maxLen) {
                    data.append("[truncated...]");
                }
            }
        }
        logger.trace("HTTP Response:\n{}", data.toString().trim());
    }
}
 
Example 18
Source File: HttpClientHandler.java    From protools with Apache License 2.0 4 votes vote down vote up
@Override
public void channelRead0(final ChannelHandlerContext ctx, final HttpObject msg) {
    if (msg instanceof FullHttpResponse) {
        final FullHttpResponse response = (FullHttpResponse) msg;

        httpReceive.setStatusCode(response.status().code())
                .setStatusText(response.status().codeAsText().toString());

        HttpHeaders headers = response.headers();
        if (httpSend.getNeedReceiveHeaders() && !headers.isEmpty()) {

            final Map<String, String> responseHeaderMap = Maps.newHashMapWithExpectedSize(headers.size());

            headers.forEach(one -> {
                responseHeaderMap.put(one.getKey(), one.getValue());
            });

            httpReceive.setResponseHeader(responseHeaderMap);
        }

        if (HttpUtil.isTransferEncodingChunked(response)) {
            if (log.isDebugEnabled()) {
                log.debug("#HTTP 内容开始{");
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("#HTTP 内容开始{");
            }
        }

        final String responseBody = response.content().toString(httpSend.getCharset());

        httpReceive.setResponseBody(responseBody);

        if (log.isDebugEnabled()) {
            log.debug(responseBody);
        }

        if (log.isDebugEnabled()) {
            log.debug("}EOF#");
        }

        final DecoderResult decoderResult = response.decoderResult();
        if (decoderResult.isFailure()) {
            Throwable cause = decoderResult.cause();
            if (log.isErrorEnabled()) {
                log.error(ToolFormat.toException(cause), cause);
            }
            httpReceive.setHaveError(true)
                    .setErrMsg(cause.getMessage())
                    .setThrowable(cause);
        } else if (response.status().code() != 200) {
            httpReceive.setHaveError(true)
                    .setErrMsg("本次请求响应码不是200,是" + response.status().code());
        }

        httpReceive.setIsDone(true);
        ctx.close();
    }
}
 
Example 19
Source File: DFHttpCliHandler.java    From dfactor with MIT License 4 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
	hasRsp = true;
	try{
		if(msg instanceof FullHttpResponse){
			int actorId = 0;
			FullHttpResponse rsp = (FullHttpResponse) msg;
			HttpHeaders headers = rsp.headers();
			long contentLen = HttpUtil.getContentLength(rsp);
			String contentType = headers.get(HttpHeaderNames.CONTENT_TYPE);
			//
			DFHttpCliRsp dfRsp = null;
			ByteBuf buf = rsp.content();
			//parse msg
			boolean isString = contentIsString(contentType);
			if(isString){  //String
				String str = null;
				if(buf != null){
					str = (String) buf.readCharSequence(buf.readableBytes(), CharsetUtil.UTF_8);
				}
				dfRsp = new DFHttpCliRspWrap(rsp.status().code(), headers,
						contentType, (int) contentLen, 
						null, str);
			}else{  //binary
				dfRsp = new DFHttpCliRspWrap(rsp.status().code(), headers,
						contentType, (int) contentLen, 
						buf, null);
			}
			//
			Object msgWrap = null;
			//decode
			if(decoder != null){
				Object tmp = decoder.onDecode(dfRsp);
				if(tmp != null){
           			msgWrap = tmp;
           		}
			}
			if(msgWrap == null){  //没有解码
           		msgWrap = dfRsp;
           		if(!isString && buf != null){
           			buf.retain();
           		}
           	}
			//检测分发
			if(dispatcher != null){
				actorId = dispatcher.onQueryMsgActorId(addrRemote.getPort(), addrRemote, msgWrap);
			}
			//
			if(actorId == 0){
            	actorId = actorIdDef;
            }
			//
			if(actorId != 0 && msgWrap != null){ //可以后续处理
				DFActorManager.get().send(requestId, actorId, 2, 
						DFActorDefine.SUBJECT_NET, 
						DFActorDefine.NET_TCP_MESSAGE,  
						msgWrap, true, session, actorId==actorIdDef?userHandler:null, false);
            }
		}
	}finally{
		ReferenceCountUtil.release(msg);
		ctx.close();
	}
}
 
Example 20
Source File: EtcdResponseHandler.java    From etcd4j with Apache License 2.0 4 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse response) throws Exception {
  final HttpResponseStatus status =response.status();
  final HttpHeaders headers = response.headers();
  final ByteBuf content = response.content();

  if (logger.isDebugEnabled()) {
    logger.debug("Received {} for {} {}",
      status.code(), this.request.getMethod().name(), this.request.getUri());
  }

  if (status.equals(HttpResponseStatus.MOVED_PERMANENTLY)
    || status.equals(HttpResponseStatus.TEMPORARY_REDIRECT)) {
    if (headers.contains(HttpHeaderNames.LOCATION)) {
      this.request.setUrl(headers.get(HttpHeaderNames.LOCATION));
      this.client.connect(this.request);
      // Closing the connection which handled the previous request.
      ctx.close();
      if (logger.isDebugEnabled()) {
        logger.debug("redirect for {} to {}",
          this.request.getHttpRequest().uri() ,
          headers.get(HttpHeaderNames.LOCATION)
        );
      }
    } else {
      this.promise.setFailure(new Exception("Missing Location header on redirect"));
    }
  } else {
    EtcdResponseDecoder<? extends Throwable> failureDecoder = failureDecoders.get(status);
    if(failureDecoder != null) {
      this.promise.setFailure(failureDecoder.decode(headers, content));
    } else if (!content.isReadable()) {
      // If connection was accepted maybe response has to be waited for
      if (!status.equals(HttpResponseStatus.OK)
        && !status.equals(HttpResponseStatus.ACCEPTED)
        && !status.equals(HttpResponseStatus.CREATED)) {
        this.promise.setFailure(new IOException(
          "Content was not readable. HTTP Status: " + status));
      }
    } else {
      try {
        this.promise.setSuccess(
          request.getResponseDecoder().decode(headers, content));
      } catch (Exception e) {
        if (e instanceof EtcdException) {
          this.promise.setFailure(e);
        } else {
          try {
            // Try to be smart, if an exception is thrown, first try to decode
            // the content and see if it is an EtcdException, i.e. an error code
            // not included in failureDecoders
            this.promise.setFailure(EtcdException.DECODER.decode(headers, content));
          } catch (Exception e1) {
            // if it fails again, set the original exception as failure
            this.promise.setFailure(e);
          }
        }
      }
    }
  }
}