本文整理匯總了Java中io.netty.handler.codec.http.HttpResponse類的典型用法代碼示例。如果您正苦於以下問題:Java HttpResponse類的具體用法?Java HttpResponse怎麽用?Java HttpResponse使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
HttpResponse類屬於io.netty.handler.codec.http包,在下文中一共展示了HttpResponse類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: channelRead
import io.netty.handler.codec.http.HttpResponse; //導入依賴的package包/類
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//客戶端channel已關閉則不轉發了
if (!clientChannel.isOpen()) {
ReferenceCountUtil.release(msg);
return;
}
HttpProxyInterceptPipeline interceptPipeline = ((HttpProxyServerHandle) clientChannel.pipeline()
.get("serverHandle")).getInterceptPipeline();
if (msg instanceof HttpResponse) {
interceptPipeline.afterResponse(clientChannel, ctx.channel(), (HttpResponse) msg);
} else if (msg instanceof HttpContent) {
interceptPipeline.afterResponse(clientChannel, ctx.channel(), (HttpContent) msg);
} else {
clientChannel.writeAndFlush(msg);
}
}
示例2: channelRead
import io.netty.handler.codec.http.HttpResponse; //導入依賴的package包/類
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// 當攔截的方法返回false直接返回,否則進入下一個handler
if(!afterHandle(ctx, msg)){
// 釋放ThreadLocal對象
DataHolder.removeAll();
HttpResponse response = HttpRenderUtil.render(null,HttpRenderUtil.CONTENT_TYPE_TEXT);
// 從該channel直接返回
ctx.channel().writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
return;
}
/**
* 提交給下一個ChannelHandler去處理
* 並且不需要調用ReferenceCountUtil.release(msg);來釋放引用計數
*/
ctx.fireChannelRead(msg);
}
示例3: setDateAndCacheHeaders
import io.netty.handler.codec.http.HttpResponse; //導入依賴的package包/類
/**
* Sets the Date and Cache headers for the HTTP Response
*
* @param response
* HTTP response
* @param fileToCache
* file to extract content type
*/
public void setDateAndCacheHeaders(HttpResponse response, File fileToCache) {
SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE));
// Date header
Calendar time = new GregorianCalendar();
response.headers().set(HttpHeaders.Names.DATE, dateFormatter.format(time.getTime()));
// Add cache headers
time.add(Calendar.SECOND, HTTP_CACHE_SECONDS);
response.headers().set(HttpHeaders.Names.EXPIRES, dateFormatter.format(time.getTime()));
response.headers().set(HttpHeaders.Names.CACHE_CONTROL, "private, max-age=" + HTTP_CACHE_SECONDS);
response.headers().set(
HttpHeaders.Names.LAST_MODIFIED, dateFormatter.format(new Date(fileToCache.lastModified())));
}
示例4: setDino
import io.netty.handler.codec.http.HttpResponse; //導入依賴的package包/類
private static HttpResponse setDino(XrpcRequest request, List<Dino> dinos) {
try {
Optional<DinoSetRequest> setRequest =
Optional.of(
DinoSetRequest.parseFrom(
CodedInputStream.newInstance(request.getData().nioBuffer())));
setRequest.ifPresent(req -> dinos.add(req.getDino()));
return Recipes.newResponse(
HttpResponseStatus.OK,
request
.getByteBuf()
.writeBytes(DinoSetReply.newBuilder().setResponseCode("OK").build().toByteArray()),
Recipes.ContentType.Application_Octet_Stream);
} catch (IOException e) {
return Recipes.newResponseBadRequest("Malformed SetDino Request: " + e.getMessage());
}
}
示例5: write
import io.netty.handler.codec.http.HttpResponse; //導入依賴的package包/類
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
LOGGER.info("[Client ({})] <= [Server ({})] : {}",
connectionInfo.getClientAddr(), connectionInfo.getServerAddr(),
msg);
if (msg instanceof HttpResponse) {
HttpResponse response = (HttpResponse) msg;
if (!response.headers().contains(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text())) {
if (streams.isEmpty()) {
throw new IllegalStateException("No active streams");
}
response.headers().add(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(),
streams.poll());
}
}
ctx.write(msg, promise);
}
示例6: setCorsResponseHeaders
import io.netty.handler.codec.http.HttpResponse; //導入依賴的package包/類
public static void setCorsResponseHeaders(HttpRequest request, HttpResponse resp, Netty4CorsConfig config) {
if (!config.isCorsSupportEnabled()) {
return;
}
String originHeader = request.headers().get(HttpHeaderNames.ORIGIN);
if (!Strings.isNullOrEmpty(originHeader)) {
final String originHeaderVal;
if (config.isAnyOriginSupported()) {
originHeaderVal = ANY_ORIGIN;
} else if (config.isOriginAllowed(originHeader) || isSameOrigin(originHeader, request.headers().get(HttpHeaderNames.HOST))) {
originHeaderVal = originHeader;
} else {
originHeaderVal = null;
}
if (originHeaderVal != null) {
resp.headers().add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, originHeaderVal);
}
}
if (config.isCredentialsAllowed()) {
resp.headers().add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
}
}
示例7: setOrigin
import io.netty.handler.codec.http.HttpResponse; //導入依賴的package包/類
private boolean setOrigin(final HttpResponse response) {
final String origin = request.headers().get(HttpHeaderNames.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;
}
示例8: setDateAndCacheHeaders
import io.netty.handler.codec.http.HttpResponse; //導入依賴的package包/類
/**
* Sets the Date and Cache headers for the HTTP Response
*
* @param response HTTP response
* @param fileToCache file to extract content type
*/
private static void setDateAndCacheHeaders(HttpResponse response, File fileToCache) {
SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE));
// Date header
Calendar time = new GregorianCalendar();
response.headers().set(HttpHeaderNames.DATE, dateFormatter.format(time.getTime()));
// Add cache headers
time.add(Calendar.SECOND, HTTP_CACHE_SECONDS);
response.headers().set(HttpHeaderNames.EXPIRES, dateFormatter.format(time.getTime()));
response.headers().set(HttpHeaderNames.CACHE_CONTROL, "private, max-age=" + HTTP_CACHE_SECONDS);
response.headers().set(
HttpHeaderNames.LAST_MODIFIED, dateFormatter.format(new Date(fileToCache.lastModified())));
}
示例9: getNettyResponse
import io.netty.handler.codec.http.HttpResponse; //導入依賴的package包/類
/**
* Get a Netty {@link HttpResponse}, committing the {@link HttpServletResponse}.
*/
public HttpResponse getNettyResponse() {
if (committed) {
return response;
}
committed = true;
HttpHeaders headers = response.headers();
if (null != contentType) {
String value = null == characterEncoding ? contentType : contentType + "; charset=" + characterEncoding;
headers.set(HttpHeaders.Names.CONTENT_TYPE, value);
}
CharSequence date = getFormattedDate();
headers.set(HttpHeaders.Names.DATE, date);
headers.set(HttpHeaders.Names.SERVER, servletContext.getServerInfoAscii());
// TODO cookies
return response;
}
示例10: setDateAndCacheHeaders
import io.netty.handler.codec.http.HttpResponse; //導入依賴的package包/類
/**
* Sets the Date and Cache headers for the HTTP Response
*
* @param response HTTP response
* @param fileToCache file to extract content type
*/
private void setDateAndCacheHeaders(HttpResponse response, File fileToCache) {
SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE));
// Date header
Calendar time = new GregorianCalendar();
response.headers().set(HttpHeaderNames.DATE, dateFormatter.format(time.getTime()));
// Add cache headers
time.add(Calendar.SECOND, HTTP_CACHE_SECONDS);
response.headers().set(HttpHeaderNames.EXPIRES, dateFormatter.format(time.getTime()));
response.headers().set(HttpHeaderNames.CACHE_CONTROL, "private, max-age=" + HTTP_CACHE_SECONDS);
response.headers().set(
HttpHeaderNames.LAST_MODIFIED, dateFormatter.format(new Date(fileToCache.lastModified())));
}
示例11: startDownTask
import io.netty.handler.codec.http.HttpResponse; //導入依賴的package包/類
public static void startDownTask(TaskInfo taskInfo, HttpRequest httpRequest,
HttpResponse httpResponse, Channel clientChannel) {
HttpHeaders httpHeaders = httpResponse.headers();
HttpDownInfo httpDownInfo = new HttpDownInfo(taskInfo, httpRequest);
HttpDownServer.DOWN_CONTENT.put(taskInfo.getId(), httpDownInfo);
httpHeaders.clear();
httpResponse.setStatus(HttpResponseStatus.OK);
httpHeaders.set(HttpHeaderNames.CONTENT_TYPE, "text/html");
String host = HttpDownServer.isDev() ? "localhost"
: ((InetSocketAddress) clientChannel.localAddress()).getHostString();
String js =
"<script>window.top.location.href='http://" + host + ":" + HttpDownServer.VIEW_SERVER_PORT
+ "/#/tasks/new/" + httpDownInfo
.getTaskInfo().getId()
+ "';</script>";
HttpContent content = new DefaultLastHttpContent();
content.content().writeBytes(js.getBytes());
httpHeaders.set(HttpHeaderNames.CONTENT_LENGTH, js.getBytes().length);
clientChannel.writeAndFlush(httpResponse);
clientChannel.writeAndFlush(content);
clientChannel.close();
}
示例12: syncRequest
import io.netty.handler.codec.http.HttpResponse; //導入依賴的package包/類
/**
* 同步請求
* @param host
* @param port
* @param request
* @return 超時返回null
*/
public HttpResponse syncRequest(String host,int port,HttpRequest request)
{
HttpResponse response=null;
synchronized (request) {
if(response==null)
{
HttpListener listener=new HttpListener(request);
NettyClient client=new NettyClient(config,new InetSocketAddress(host, port),new HttpClientInitHandler(listener));
client.start();
response=listener.waitResponse();//阻塞等待結果
client.stop();
}
}
return response;
}
示例13: filterRequest
import io.netty.handler.codec.http.HttpResponse; //導入依賴的package包/類
@Override
public HttpResponse filterRequest(HttpRequest httpRequest, HttpMessageContents httpMessageContents, HttpMessageInfo httpMessageInfo) {
replayingState.addHttpRequestToQueue(httpMessageInfo.getOriginalRequest());
replayingState.setHttpLock(false);
for (ConditionsUpdater conditionsUpdater: conditionsUpdaters) {
if (conditionsUpdater.shouldUpdate().test(httpRequest)) {
try {
URL url = new URL(httpRequest.getUri());
String event = url.getQuery();
conditionsUpdater.updater().update(replayingState, event);
} catch (MalformedURLException e) {
logger.error(e.getMessage(), e);
}
}
}
return null;
}
示例14: filterRequest
import io.netty.handler.codec.http.HttpResponse; //導入依賴的package包/類
@Override
public HttpResponse filterRequest(HttpRequest httpRequest, HttpMessageContents httpMessageContents, HttpMessageInfo httpMessageInfo) {
for (EventDetector eventDetector: eventDetectors) {
if (eventDetector.canDetectPredicate().test(httpRequest)) {
try {
Optional<Map<String, String>> optionalEvent = eventDetector.getConverter().convert(httpRequest);
if (optionalEvent.isPresent()) {
Map<String, String> event = optionalEvent.get();
recordingState.storeTestCaseStep(event);
logger.info("Recorded event {}", event);
}
} catch (UnsupportedEncodingException | MalformedURLException e) {
logger.error("Error while trying to convert test case step", e);
}
}
}
return null;
}
示例15: afterResponse
import io.netty.handler.codec.http.HttpResponse; //導入依賴的package包/類
@Override
public void afterResponse(Channel clientChannel, Channel proxyChannel, HttpResponse httpResponse,
HttpProxyInterceptPipeline pipeline) throws Exception {
if (HttpDownUtil.checkReferer(pipeline.getHttpRequest(), "^https?://pan.baidu.com/disk/home.*$")
&& HttpDownUtil.checkUrl(pipeline.getHttpRequest(), "^.*method=batchdownload.*$")) {
HttpHeaders resHeaders = httpResponse.headers();
long fileSize = HttpDownUtil.getDownFileSize(resHeaders);
//百度合並下載分段最多為16M
int connections = (int) Math.ceil(fileSize / CHUNK_16M);
TaskInfo taskInfo = new TaskInfo()
.setId(UUID.randomUUID().toString())
.setFileName(HttpDownUtil.getDownFileName(pipeline.getHttpRequest(), resHeaders))
.setTotalSize(HttpDownUtil.getDownFileSize(resHeaders))
.setConnections(connections)
.setSupportRange(true);
HttpDownUtil.startDownTask(taskInfo, pipeline.getHttpRequest(), httpResponse, clientChannel);
return;
}
pipeline.afterResponse(clientChannel, proxyChannel, httpResponse);
}