下面列出了 io.netty.handler.codec.http.HttpResponseStatus # code ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
protected void sanitizeHeadersBeforeEncode(HttpResponse msg, boolean isAlwaysEmpty) {
if (isAlwaysEmpty) {
HttpResponseStatus status = msg.status();
if (status.codeClass() == HttpStatusClass.INFORMATIONAL
|| status.code() == HttpResponseStatus.NO_CONTENT.code()) {
// Stripping Content-Length:
// See https://tools.ietf.org/html/rfc7230#section-3.3.2
msg.headers().remove(HttpHeaderNames.CONTENT_LENGTH);
// Stripping Transfer-Encoding:
// See https://tools.ietf.org/html/rfc7230#section-3.3.1
msg.headers().remove(HttpHeaderNames.TRANSFER_ENCODING);
} else if (status.code() == HttpResponseStatus.RESET_CONTENT.code()) {
// Stripping Transfer-Encoding:
msg.headers().remove(HttpHeaderNames.TRANSFER_ENCODING);
// Set Content-Length: 0
// https://httpstatuses.com/205
msg.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, 0);
}
}
}
@Override
protected boolean isContentAlwaysEmpty(HttpResponse msg) {
// Correctly handle special cases as stated in:
// https://tools.ietf.org/html/rfc7230#section-3.3.3
HttpResponseStatus status = msg.status();
if (status.codeClass() == HttpStatusClass.INFORMATIONAL) {
if (status.code() == HttpResponseStatus.SWITCHING_PROTOCOLS.code()) {
// We need special handling for WebSockets version 00 as it will include an body.
// Fortunally this version should not really be used in the wild very often.
// See https://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-00#section-1.2
return msg.headers().contains(HttpHeaderNames.SEC_WEBSOCKET_VERSION);
}
return true;
}
return status.code() == HttpResponseStatus.NO_CONTENT.code()
|| status.code() == HttpResponseStatus.NOT_MODIFIED.code()
|| status.code() == HttpResponseStatus.RESET_CONTENT.code();
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
try {
if (msg instanceof HttpResponse) {
HttpResponse response = (HttpResponse) msg;
HttpResponseStatus status = response.status();
this.httpCode = status.code();
}
if (msg instanceof HttpContent) {
buffer.append(((HttpContent) msg).content().toString(StandardCharsets.UTF_8));
if (msg instanceof LastHttpContent) {
ctx.close();
reply.complete(new SimpleHttpResponse(httpCode, buffer.toString()));
}
}
} finally {
ReferenceCountUtil.release(msg);
}
}
static public void sendErrorResponse(ChannelHandlerContext ctx, HttpResponseStatus status, Exception ex) {
try {
TimelyException te = new TimelyException(status.code(), ex.getMessage(), ex.getMessage());
String json = mapper.writeValueAsString(te);
ctx.writeAndFlush(new TextWebSocketFrame(json));
} catch (JsonProcessingException e) {
LOG.error("Error serializing exception");
}
}
@Nullable
@Override
public Integer getResponseHttpStatus(@Nullable HttpResponse response) {
if (response == null) {
return null;
}
HttpResponseStatus statusObj = response.status();
if (statusObj == null) {
return null;
}
return statusObj.code();
}
public void trackResponse(HttpRequest request, FullHttpResponse response) {
// check if tenantId is being tracked by JMX TenantTrackerMBean and log the response if it is
// HttpRequest is needed for original request uri and tenantId
if (request == null) return;
if (response == null) return;
String tenantId = findTid( request.getUri() );
if (isTracking(tenantId)) {
HttpResponseStatus status = response.getStatus();
String messageBody = response.content().toString(Constants.DEFAULT_CHARSET);
// get parameters
String queryParams = getQueryParameters(request);
// get headers
String headers = "";
for (String headerName : response.headers().names()) {
headers += "\n" + headerName + "\t" + response.headers().get(headerName);
}
// get response content
String responseContent = "";
if ((messageBody != null) && (!messageBody.isEmpty())) {
responseContent = "\nRESPONSE_CONTENT:\n" + messageBody;
}
String logMessage = "[TRACKER] " +
"Response for tenantId " + tenantId + " " + request.getMethod() + " request " + request.getUri() + queryParams +
"\nRESPONSE_STATUS: " + status.code() +
"\nRESPONSE HEADERS: " + headers +
responseContent;
log.info(logMessage);
}
}
public StatusMessageException(HttpResponseStatus status, String errorMessage) {
super(errorMessage);
this.errorCode = status.code();
}
public StatusMessageException(HttpResponseStatus status) {
super(status.reasonPhrase());
this.errorCode = status.code();
}
public static void sendError(
ChannelHandlerContext ctx, HttpResponseStatus status, Throwable t) {
ErrorResponse error =
new ErrorResponse(status.code(), t.getClass().getSimpleName(), t.getMessage());
sendJsonResponse(ctx, error, status);
}
public static void sendError(
ChannelHandlerContext ctx, HttpResponseStatus status, Throwable t, String msg) {
ErrorResponse error = new ErrorResponse(status.code(), t.getClass().getSimpleName(), msg);
sendJsonResponse(ctx, error, status);
}
public HttpException(HttpResponseStatus status) {
this(status, "Http Error " + status.code() + ": " + status.reasonPhrase(), null);
}
public HttpException(HttpResponseStatus status, Throwable cause) {
this(status, "Http Error " + status.code() + ": " + status.reasonPhrase(), cause);
}
public HttpException(HttpResponseStatus status, String message, Throwable cause) {
super(message, cause);
this.statusCode = status.code();
}
public static void sendError(
ChannelHandlerContext ctx, HttpResponseStatus status, Throwable t) {
ErrorResponse error =
new ErrorResponse(status.code(), t.getClass().getSimpleName(), t.getMessage());
sendJsonResponse(ctx, error, status);
}
public static void sendError(
ChannelHandlerContext ctx, HttpResponseStatus status, Throwable t, String msg) {
ErrorResponse error = new ErrorResponse(status.code(), t.getClass().getSimpleName(), msg);
sendJsonResponse(ctx, error, status);
}
@NotNull
// @VisibleForTesting
static <Send> Func1<HttpClientResponse<ByteBuf>, Observable<ByteBuf>> verifyResponseOk(
@NotNull final Send subscription,
@NotNull final AtomicReference<String> mesosStreamId,
@NotNull final String receiveMediaType
) {
return resp -> {
final HttpResponseStatus status = resp.getStatus();
final int code = status.code();
final String contentType = resp.getHeaders().get(HttpHeaderNames.CONTENT_TYPE);
if (code == 200 && receiveMediaType.equals(contentType)) {
if (resp.getHeaders().contains(MESOS_STREAM_ID)) {
final String streamId = resp.getHeaders().get(MESOS_STREAM_ID);
mesosStreamId.compareAndSet(null, streamId);
}
return resp.getContent();
} else {
final HttpResponseHeaders headers = resp.getHeaders();
return ResponseUtils.attemptToReadErrorResponse(resp).flatMap(msg -> {
final List<Map.Entry<String, String>> entries = headers.entries();
final MesosClientErrorContext context = new MesosClientErrorContext(code, msg, entries);
if (code == 200) {
// this means that even though we got back a 200 it's not the sort of response we were expecting
// For example hitting an endpoint that returns an html document instead of a document of type
// `receiveMediaType`
throw new MesosException(
subscription,
context.withMessage(
String.format(
"Response had Content-Type \"%s\" expected \"%s\"",
contentType,
receiveMediaType
)
)
);
} else if (400 <= code && code < 500) {
throw new Mesos4xxException(subscription, context);
} else if (500 <= code && code < 600) {
throw new Mesos5xxException(subscription, context);
} else {
LOGGER.warn("Unhandled error: context = {}", context);
// This shouldn't actually ever happen, but it's here for completeness of the if-else tree
// that always has to result in an exception being thrown so the compiler is okay with this
// lambda
throw new IllegalStateException("Unhandled error");
}
});
}
};
}
@Override public int statusCode() {
HttpResponseStatus status = delegate.status();
return status != null ? status.code() : 0;
}
JsonServiceException(HttpResponseStatus status, Throwable cause) {
super("", cause);
this.statusCode = status.code();
}
JsonServiceException(HttpResponseStatus status, String message) {
super(message);
this.statusCode = status.code();
}
JsonServiceException(HttpResponseStatus status) {
super();
this.statusCode = status.code();
}