下面列出了 io.netty.handler.codec.http.HttpResponse # headers ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void handleUpnpMsearchResponse(DatagramPacket packet, HttpResponse response) {
HttpHeaders headers = response.headers();
if (!parseUsnHeader(headers)) {
log.trace("dropping upnp m-search response with bad usn");
return;
}
String url = headers.get("LOCATION");
long maxAge = parseCacheControlHeader(headers);
if (log.isTraceEnabled()) {
log.trace("upnp msearch response: cache={}s, sender={}, uuid={}, class={}, namespace={}, type={}, version={}\n{}",
TimeUnit.SECONDS.convert(maxAge,TimeUnit.NANOSECONDS),
packet.sender(),
usn.deviceUuid,
usn.clazz,
usn.namespace,
usn.type,
usn.version, response);
}
IrisUpnpService.poke(packet.sender(), usn, maxAge, url, headers);
}
private HttpHeadersFrame createHttpHeadersFrame(HttpResponse httpResponse)
throws Exception {
// Get the Stream-ID from the headers
int streamId = HttpHeaders.getIntHeader(httpResponse, "X-SPDY-Stream-ID");
httpResponse.headers().remove("X-SPDY-Stream-ID");
// The Connection, Keep-Alive, Proxy-Connection, and Transfer-Encoding
// headers are not valid and MUST not be sent.
httpResponse.headers().remove(HttpHeaders.Names.CONNECTION);
httpResponse.headers().remove("Keep-Alive");
httpResponse.headers().remove("Proxy-Connection");
httpResponse.headers().remove(HttpHeaders.Names.TRANSFER_ENCODING);
HttpHeadersFrame httpHeadersFrame = new DefaultHttpHeadersFrame(streamId);
// Unfold the first line of the response into name/value pairs
httpHeadersFrame.headers().set(":status", httpResponse.getStatus().code());
// Transfer the remaining HTTP headers
for (Map.Entry<String, String> entry : httpResponse.headers()) {
httpHeadersFrame.headers().add(entry.getKey(), entry.getValue());
}
return httpHeadersFrame;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (needsToFilterUpgradeResponse && msg instanceof HttpResponse) {
needsToFilterUpgradeResponse = false;
final HttpResponse res = (HttpResponse) msg;
if (res.status().code() == HttpResponseStatus.SWITCHING_PROTOCOLS.code()) {
final HttpHeaders headers = res.headers();
if (!headers.contains(HttpHeaderNames.UPGRADE)) {
headers.set(HttpHeaderNames.UPGRADE,
Http2CodecUtil.HTTP_UPGRADE_PROTOCOL_NAME);
}
}
if (!needsToFilterUpgradeRequest) {
ctx.pipeline().remove(this);
}
}
ctx.fireChannelRead(msg);
}
protected void captureResponseHeaderSize(HttpResponse httpResponse) {
String statusLine = httpResponse.protocolVersion().toString() + ' ' + httpResponse.status().toString();
// +2 => CRLF after status line, +4 => header/data separation
long responseHeadersSize = statusLine.length() + 6;
HttpHeaders headers = httpResponse.headers();
responseHeadersSize += BrowserUpHttpUtil.getHeaderSize(headers);
harEntry.getResponse().setHeadersSize(responseHeadersSize);
}
protected void captureResponseHeaders(HttpResponse httpResponse) {
HttpHeaders headers = httpResponse.headers();
headers.entries().forEach(header -> {
HarHeader harHeader = new HarHeader();
harHeader.setName(header.getKey());
harHeader.setValue(header.getValue());
harEntry.getResponse().getHeaders().add(harHeader);
});
}
@SuppressWarnings("deprecation")
private SpdyHeadersFrame createHeadersFrame(HttpResponse httpResponse) throws Exception {
// Get the Stream-ID from the headers
final HttpHeaders httpHeaders = httpResponse.headers();
int streamId = httpHeaders.getInt(SpdyHttpHeaders.Names.STREAM_ID);
httpHeaders.remove(SpdyHttpHeaders.Names.STREAM_ID);
// The Connection, Keep-Alive, Proxy-Connection, and Transfer-Encoding
// headers are not valid and MUST not be sent.
httpHeaders.remove(HttpHeaderNames.CONNECTION);
httpHeaders.remove("Keep-Alive");
httpHeaders.remove("Proxy-Connection");
httpHeaders.remove(HttpHeaderNames.TRANSFER_ENCODING);
SpdyHeadersFrame spdyHeadersFrame;
if (SpdyCodecUtil.isServerId(streamId)) {
spdyHeadersFrame = new DefaultSpdyHeadersFrame(streamId, validateHeaders);
} else {
spdyHeadersFrame = new DefaultSpdySynReplyFrame(streamId, validateHeaders);
}
SpdyHeaders frameHeaders = spdyHeadersFrame.headers();
// Unfold the first line of the response into name/value pairs
frameHeaders.set(SpdyHeaders.HttpNames.STATUS, httpResponse.status().codeAsText());
frameHeaders.set(SpdyHeaders.HttpNames.VERSION, httpResponse.protocolVersion().text());
// Transfer the remaining HTTP headers
Iterator<Entry<CharSequence, CharSequence>> itr = httpHeaders.iteratorCharSequence();
while (itr.hasNext()) {
Map.Entry<CharSequence, CharSequence> entry = itr.next();
final CharSequence headerName =
headersToLowerCase ? AsciiString.of(entry.getKey()).toLowerCase() : entry.getKey();
spdyHeadersFrame.headers().add(headerName, entry.getValue());
}
currentStreamId = streamId;
spdyHeadersFrame.setLast(isLast(httpResponse));
return spdyHeadersFrame;
}
protected void captureResponseHeaderSize(HttpResponse httpResponse) {
String statusLine = httpResponse.getProtocolVersion().toString() + ' ' + httpResponse.getStatus().toString();
// +2 => CRLF after status line, +4 => header/data separation
long responseHeadersSize = statusLine.length() + 6;
HttpHeaders headers = httpResponse.headers();
responseHeadersSize += BrowserMobHttpUtil.getHeaderSize(headers);
harEntry.getResponse().setHeadersSize(responseHeadersSize);
}
@Override
protected void channelRead0(
ChannelHandlerContext channelHandlerContext,
FullHttpRequest fullHttpRequest
) throws Exception {
logger.warn("Received {}", fullHttpRequest);
if (HttpUtil.is100ContinueExpected(fullHttpRequest)) {
channelHandlerContext.writeAndFlush(
new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1,
HttpResponseStatus.CONTINUE));
}
HttpResponse response = new DefaultHttpResponse(
fullHttpRequest.protocolVersion(),
HttpResponseStatus.OK);
HttpHeaders headers = response.headers();
headers.set(CONTENT_TYPE, "text/html; charset=UTF-8");
ByteBuf responseContent = Unpooled.copiedBuffer("OK", CharsetUtil.UTF_8);
boolean keepAlive = HttpUtil.isKeepAlive(fullHttpRequest);
if (keepAlive) {
headers.set(CONTENT_LENGTH, responseContent.readableBytes());
headers.set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
}
// write response
channelHandlerContext.write(response);
channelHandlerContext.write(responseContent);
ChannelFuture future = channelHandlerContext.writeAndFlush(
LastHttpContent.EMPTY_LAST_CONTENT);
// Decide whether to close the connection or not.
if (!keepAlive) {
future.addListener(ChannelFutureListener.CLOSE);
}
}
protected void captureResponseHeaderSize(HttpResponse httpResponse) {
Log.e("InnerHandle", "captureResponseHeaderSize " + harEntry.getId());
String statusLine = httpResponse.getProtocolVersion().toString() + ' ' + httpResponse.getStatus().toString();
// +2 => CRLF after status line, +4 => header/data separation
long responseHeadersSize = statusLine.length() + 6;
HttpHeaders headers = httpResponse.headers();
responseHeadersSize += BrowserMobHttpUtil.getHeaderSize(headers);
harResponse.getResponse().setHeadersSize(responseHeadersSize);
}
protected void captureResponseHeaders(HttpResponse httpResponse) {
Log.e("InnerHandle", "captureResponseHeaders " + harEntry.getId());
HttpHeaders headers = httpResponse.headers();
for (Map.Entry<String, String> header : headers.entries()) {
harResponse.getResponse().getHeaders().add(new HarNameValuePair(header.getKey(), header.getValue()));
harResponse.addHeader(header.getKey(), header.getValue());
}
}
final boolean notRedirected(HttpResponse response) {
if (isFollowRedirect() && followRedirectPredicate.test(this, this)) {
if (log.isDebugEnabled()) {
log.debug(format(channel(), "Received redirect location: {}"),
response.headers()
.entries()
.toString());
}
redirecting = new RedirectClientException(response.headers());
return false;
}
return true;
}
final void setNettyResponse(HttpResponse nettyResponse) {
ResponseState state = responseState;
if (state == null) {
this.responseState =
new ResponseState(nettyResponse, nettyResponse.headers(), cookieDecoder);
}
}
protected void captureResponseHeaderSize(HttpResponse httpResponse) {
String statusLine = httpResponse.getProtocolVersion().toString() + ' ' + httpResponse.getStatus().toString();
// +2 => CRLF after status line, +4 => header/data separation
long responseHeadersSize = statusLine.length() + 6;
HttpHeaders headers = httpResponse.headers();
responseHeadersSize += BrowserMobHttpUtil.getHeaderSize(headers);
harEntry.getResponse().setHeadersSize(responseHeadersSize);
}
@SuppressWarnings("deprecation")
private SpdyHeadersFrame createHeadersFrame(HttpResponse httpResponse) throws Exception {
// Get the Stream-ID from the headers
final HttpHeaders httpHeaders = httpResponse.headers();
int streamId = SpdyHttpHeaders.getStreamId(httpResponse);
httpHeaders.remove(SpdyHttpHeaders.Names.STREAM_ID);
// The Connection, Keep-Alive, Proxy-Connection, and Transfer-Encoding
// headers are not valid and MUST not be sent.
httpHeaders.remove(HttpHeaders.Names.CONNECTION);
httpHeaders.remove("Keep-Alive");
httpHeaders.remove("Proxy-Connection");
httpHeaders.remove(HttpHeaders.Names.TRANSFER_ENCODING);
SpdyHeadersFrame spdyHeadersFrame;
if (SpdyCodecUtil.isServerId(streamId)) {
spdyHeadersFrame = new DefaultSpdyHeadersFrame(streamId);
} else {
spdyHeadersFrame = new DefaultSpdySynReplyFrame(streamId);
}
SpdyHeaders frameHeaders = spdyHeadersFrame.headers();
// Unfold the first line of the response into name/value pairs
frameHeaders.set(SpdyHeaders.HttpNames.STATUS, httpResponse.getStatus().code());
frameHeaders.set(SpdyHeaders.HttpNames.VERSION, httpResponse.getProtocolVersion());
// Transfer the remaining HTTP headers
for (Map.Entry<String, String> entry: httpHeaders) {
spdyHeadersFrame.headers().add(entry.getKey(), entry.getValue());
}
currentStreamId = streamId;
spdyHeadersFrame.setLast(isLast(httpResponse));
return spdyHeadersFrame;
}
private HttpResponseMessage buildZuulHttpResponse(final HttpResponse httpResponse, final StatusCategory statusCategory, final Throwable ex) {
startedSendingResponseToClient = true;
// Translate the netty HttpResponse into a zuul HttpResponseMessage.
final SessionContext zuulCtx = context;
final int respStatus = httpResponse.status().code();
final HttpResponseMessage zuulResponse = new HttpResponseMessageImpl(zuulCtx, zuulRequest, respStatus);
final Headers respHeaders = zuulResponse.getHeaders();
for (Map.Entry<String, String> entry : httpResponse.headers()) {
respHeaders.add(entry.getKey(), entry.getValue());
}
// Try to decide if this response has a body or not based on the headers (as we won't yet have
// received any of the content).
// NOTE that we also later may override this if it is Chunked encoding, but we receive
// a LastHttpContent without any prior HttpContent's.
if (HttpUtils.hasChunkedTransferEncodingHeader(zuulResponse) || HttpUtils.hasNonZeroContentLengthHeader(zuulResponse)) {
zuulResponse.setHasBody(true);
}
// Store this original response info for future reference (ie. for metrics and access logging purposes).
zuulResponse.storeInboundResponse();
channelCtx.channel().attr(ATTR_ZUUL_RESP).set(zuulResponse);
if (httpResponse instanceof DefaultFullHttpResponse) {
final ByteBuf chunk = ((DefaultFullHttpResponse) httpResponse).content();
zuulResponse.bufferBodyContents(new DefaultLastHttpContent(chunk));
}
// Invoke any Ribbon execution listeners.
// Request was a success even if server may have responded with an error code 5XX, except for 503.
if (originConn != null) {
if (statusCategory == ZuulStatusCategory.FAILURE_ORIGIN_THROTTLED) {
origin.onRequestExecutionFailed(zuulRequest, originConn.getServer(), attemptNum,
new ClientException(ClientException.ErrorType.SERVER_THROTTLED));
}
else {
origin.onRequestExecutionSuccess(zuulRequest, zuulResponse, originConn.getServer(), attemptNum);
}
}
// Collect some info about the received response.
origin.recordFinalResponse(zuulResponse);
origin.recordFinalError(zuulRequest, ex);
origin.getProxyTiming(zuulRequest).end();
zuulCtx.set(CommonContextKeys.STATUS_CATGEORY, statusCategory);
zuulCtx.setError(ex);
zuulCtx.put("origin_http_status", Integer.toString(respStatus));
return transformResponse(zuulResponse);
}
public SegmentedHttp1Response(HttpResponse delegate, TraceInfo traceInfo) {
this.delegate = delegate;
this.headers = new Http1Headers(delegate.headers());
this.traceInfo = traceInfo == null ? new TraceInfo(headers) : traceInfo;
}
@Override
public void handleMessage(Object msg) {
try {
//log.info("Got message: " + msg.getClass().getName());
if (msg instanceof HttpResponse) {
HttpResponse res = (HttpResponse) msg;
responseBuilder = request.createResponseBuilder(HttpStatus.valueOf(res.status().code()));
for (Map.Entry<String, String> entry : res.headers()) {
responseBuilder.header(entry.getKey(), entry.getValue());
}
}
if (msg instanceof HttpContent) {
HttpContent content = (HttpContent) msg;
if (baos == null) {
// todo what is right size?
baos = createByteStream();
}
int readable = content.content().readableBytes();
for (int i = 0; i < readable; i++) {
baos.write(content.content().readByte());
}
}
if (msg instanceof FileRegion) {
FileRegion file = (FileRegion) msg;
if (file.count() > 0 && file.transferred() < file.count()) {
if (baos == null)
baos = createByteStream();
if (byteChannel == null)
byteChannel = Channels.newChannel(baos);
file.transferTo(byteChannel, file.transferred());
}
}
if (msg instanceof LastHttpContent) {
responseBuilder.body(baos.toByteArray());
future.complete(responseBuilder.build());
}
} catch (Throwable ex) {
future.completeExceptionally(ex);
} finally {
ReferenceCountUtil.release(msg);
}
}
@Override
public void afterResponse(Channel clientChannel, Channel proxyChannel, HttpResponse httpResponse,
HttpProxyInterceptPipeline pipeline) throws Exception {
if (!matchFlag) {
super.afterResponse(clientChannel, proxyChannel, httpResponse, pipeline);
return;
}
if ((httpResponse.status().code() + "").indexOf("20") == 0) { //响应码为20x
HttpHeaders httpResHeaders = httpResponse.headers();
String accept = pipeline.getHttpRequest().headers().get(HttpHeaderNames.ACCEPT);
String contentType = httpResHeaders.get(HttpHeaderNames.CONTENT_TYPE);
//有两种情况进行下载 1.url后缀为.xxx 2.带有CONTENT_DISPOSITION:ATTACHMENT响应头
String disposition = httpResHeaders.get(HttpHeaderNames.CONTENT_DISPOSITION);
if (accept != null
&& accept.matches("^.*text/html.*$")
&& ((disposition != null
&& disposition.contains(HttpHeaderValues.ATTACHMENT)
&& disposition.contains(HttpHeaderValues.FILENAME))
|| isDownContentType(contentType))) {
downFlag = true;
}
HttpRequestInfo httpRequestInfo = (HttpRequestInfo) pipeline.getHttpRequest();
if (downFlag) { //如果是下载
LOGGER.debug("=====================下载===========================\n" +
pipeline.getHttpRequest().toString() + "\n" +
"------------------------------------------------" +
httpResponse.toString() + "\n" +
"================================================");
proxyChannel.close();//关闭嗅探下载连接
httpRequestInfo.setRequestProto(new RequestProto(pipeline.getRequestProto().getHost(), pipeline.getRequestProto().getPort(), pipeline.getRequestProto().getSsl()));
HttpRequestForm requestForm = HttpRequestForm.parse(httpRequestInfo);
HttpResponseInfo responseInfo = HttpDownUtil.getHttpResponseInfo(httpRequestInfo, null, null, (NioEventLoopGroup) clientChannel.eventLoop().parent());
httpResponse.headers().clear();
httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html");
httpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
String js = "<script type=\"text/javascript\">window.history.go(-1)</script>";
HttpContent httpContent = new DefaultLastHttpContent();
httpContent.content().writeBytes(js.getBytes());
httpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, httpContent.content().readableBytes());
clientChannel.writeAndFlush(httpResponse);
clientChannel.writeAndFlush(httpContent);
clientChannel.close();
ObjectMapper objectMapper = new ObjectMapper();
String requestParam = URLEncoder.encode(objectMapper.writeValueAsString(requestForm), "utf-8");
String responseParam = URLEncoder.encode(objectMapper.writeValueAsString(responseInfo), "utf-8");
String uri = "/#/tasks?request=" + requestParam + "&response=" + responseParam;
DownApplication.INSTANCE.loadUri(uri, false);
return;
} else {
if (httpRequestInfo.content() != null) {
httpRequestInfo.setContent(null);
}
}
}
super.afterResponse(clientChannel, proxyChannel, httpResponse, pipeline);
}
protected void captureResponseHeaders(HttpResponse httpResponse) {
HttpHeaders headers = httpResponse.headers();
for (Map.Entry<String, String> header : headers.entries()) {
harEntry.getResponse().getHeaders().add(new HarNameValuePair(header.getKey(), header.getValue()));
}
}
@Override
protected CouchbaseResponse decodeResponse(final ChannelHandlerContext ctx, final HttpObject msg) throws Exception {
ConfigRequest request = currentRequest();
CouchbaseResponse response = null;
if (msg instanceof HttpResponse) {
responseHeader = (HttpResponse) msg;
if (request instanceof BucketStreamingRequest) {
response = handleBucketStreamingResponse(ctx, responseHeader);
}
if (responseContent != null) {
responseContent.clear();
} else {
responseContent = ctx.alloc().buffer();
}
}
if (msg instanceof HttpContent) {
responseContent.writeBytes(((HttpContent) msg).content());
if (streamingConfigObservable != null) {
maybePushConfigChunk();
}
}
if (msg instanceof LastHttpContent) {
if (request instanceof BucketStreamingRequest) {
if (streamingConfigObservable != null) {
streamingConfigObservable.onCompleted();
streamingConfigObservable = null;
}
finishedDecoding();
return null;
}
ResponseStatus status = ResponseStatusConverter.fromHttp(responseHeader.getStatus().code());
String body = responseContent.readableBytes() > 0
? responseContent.toString(CHARSET) : responseHeader.getStatus().reasonPhrase();
if (request instanceof BucketConfigRequest) {
response = new BucketConfigResponse(body, status);
} else if (request instanceof ClusterConfigRequest) {
response = new ClusterConfigResponse(body, status);
} else if (request instanceof BucketsConfigRequest) {
response = new BucketsConfigResponse(body, status);
} else if (request instanceof GetDesignDocumentsRequest) {
response = new GetDesignDocumentsResponse(body, status, request);
} else if (request instanceof RemoveBucketRequest) {
response = new RemoveBucketResponse(status);
} else if (request instanceof InsertBucketRequest) {
response = new InsertBucketResponse(body, status);
} else if (request instanceof UpdateBucketRequest) {
response = new UpdateBucketResponse(body, status);
} else if (request instanceof FlushRequest) {
boolean done = responseHeader.getStatus().code() != 201;
response = new FlushResponse(done, body, status);
} else if (request instanceof GetUsersRequest) {
response = new GetUsersResponse(body, status, request);
} else if (request instanceof UpsertUserRequest) {
response = new UpsertUserResponse(body, status);
} else if (request instanceof RemoveUserRequest) {
response = new RemoveUserResponse(status);
} else if (request instanceof RestApiRequest) {
response = new RestApiResponse((RestApiRequest) request, responseHeader.getStatus(),
responseHeader.headers(), body);
}
finishedDecoding();
}
return response;
}