本文整理匯總了Java中io.netty.handler.codec.http.HttpVersion類的典型用法代碼示例。如果您正苦於以下問題:Java HttpVersion類的具體用法?Java HttpVersion怎麽用?Java HttpVersion使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
HttpVersion類屬於io.netty.handler.codec.http包,在下文中一共展示了HttpVersion類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: newResponse
import io.netty.handler.codec.http.HttpVersion; //導入依賴的package包/類
/**
* Returns a full HTTP response with the specified status, content type, and custom headers.
*
* <p>Headers should be specified as a map of strings. For example, to allow CORS, add the
* following key and value: "access-control-allow-origin", "http://foo.example"
*
* <p>If content type or content length are passed in as custom headers, they will be ignored.
* Instead, content type will be as specified by the parameter contentType and content length will
* be the length of the parameter contentLength.
*/
public static FullHttpResponse newResponse(
HttpResponseStatus status,
ByteBuf payload,
ContentType contentType,
Map<String, String> customHeaders) {
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, payload);
if (customHeaders != null) {
for (Map.Entry<String, String> entry : customHeaders.entrySet()) {
response.headers().set(entry.getKey(), entry.getValue());
}
}
response.headers().set(CONTENT_TYPE, contentType.value);
response.headers().setInt(CONTENT_LENGTH, payload.readableBytes());
return response;
}
示例2: shouldHandlerRequestAndResponse
import io.netty.handler.codec.http.HttpVersion; //導入依賴的package包/類
@Test
public void shouldHandlerRequestAndResponse() {
inboundChannel.pipeline().addLast(handler);
DefaultFullHttpRequest req = new DefaultFullHttpRequest(
HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
inboundChannel.write(req);
assertEquals(1, inboundChannel.outboundMessages().size());
Object outboundReq = inboundChannel.outboundMessages().poll();
assertTrue(outboundReq instanceof ByteBuf);
assertEquals("GET / HTTP/1.1\r\n\r\n", new String(readBytes((ByteBuf) outboundReq)));
DefaultFullHttpResponse resp = new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
assertFalse(inboundChannel.writeInbound(resp));
assertEquals(1, outboundChannel.outboundMessages().size());
assertEquals(resp, outboundChannel.outboundMessages().poll());
resp.release();
}
示例3: shouldPendingRequests
import io.netty.handler.codec.http.HttpVersion; //導入依賴的package包/類
@Test
public void shouldPendingRequests() {
inboundChannel.pipeline().addLast(handler);
DefaultFullHttpRequest req = new DefaultFullHttpRequest(
HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
// First request
inboundChannel.write(req.retain());
assertEquals(1, inboundChannel.outboundMessages().size());
assertTrue(inboundChannel.outboundMessages().poll() instanceof ByteBuf);
// Second request
inboundChannel.write(req);
// Should pending second request
assertTrue(inboundChannel.outboundMessages().isEmpty());
}
示例4: shouldClearPendingRequests
import io.netty.handler.codec.http.HttpVersion; //導入依賴的package包/類
@Test
public void shouldClearPendingRequests() {
inboundChannel.pipeline().addLast(handler);
DefaultFullHttpRequest req = new DefaultFullHttpRequest(
HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
// First request
inboundChannel.write(req.retain());
assertEquals(1, req.refCnt());
assertEquals(1, inboundChannel.outboundMessages().size());
assertTrue(inboundChannel.outboundMessages().poll() instanceof ByteBuf);
// Second request
inboundChannel.write(req);
assertEquals(1, req.refCnt());
assertTrue(inboundChannel.outboundMessages().isEmpty());
inboundChannel.close();
assertEquals(0, req.refCnt());
}
示例5: testReleaseOnSendToClosedChannel
import io.netty.handler.codec.http.HttpVersion; //導入依賴的package包/類
public void testReleaseOnSendToClosedChannel() {
final Settings settings = Settings.builder().build();
final NamedXContentRegistry registry = xContentRegistry();
try (Netty4HttpServerTransport httpServerTransport =
new Netty4HttpServerTransport(settings, networkService, bigArrays, threadPool, registry, new NullDispatcher())) {
final FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
final EmbeddedChannel embeddedChannel = new EmbeddedChannel();
final Netty4HttpRequest request = new Netty4HttpRequest(registry, httpRequest, embeddedChannel);
final HttpPipelinedRequest pipelinedRequest = randomBoolean() ? new HttpPipelinedRequest(request.request(), 1) : null;
final Netty4HttpChannel channel =
new Netty4HttpChannel(httpServerTransport, request, pipelinedRequest, randomBoolean(), threadPool.getThreadContext());
final TestResponse response = new TestResponse(bigArrays);
assertThat(response.content(), instanceOf(Releasable.class));
embeddedChannel.close();
channel.sendResponse(response);
// ESTestCase#after will invoke ensureAllArraysAreReleased which will fail if the response content was not released
}
}
示例6: executeRequest
import io.netty.handler.codec.http.HttpVersion; //導入依賴的package包/類
private FullHttpResponse executeRequest(final Settings settings, final String originValue, final String host) {
// construct request and send it over the transport layer
try (Netty4HttpServerTransport httpServerTransport =
new Netty4HttpServerTransport(settings, networkService, bigArrays, threadPool, xContentRegistry(),
new NullDispatcher())) {
httpServerTransport.start();
final FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
if (originValue != null) {
httpRequest.headers().add(HttpHeaderNames.ORIGIN, originValue);
}
httpRequest.headers().add(HttpHeaderNames.HOST, host);
final WriteCapturingChannel writeCapturingChannel = new WriteCapturingChannel();
final Netty4HttpRequest request = new Netty4HttpRequest(xContentRegistry(), httpRequest, writeCapturingChannel);
Netty4HttpChannel channel =
new Netty4HttpChannel(httpServerTransport, request, null, randomBoolean(), threadPool.getThreadContext());
channel.sendResponse(new TestResponse());
// get the response
List<Object> writtenObjects = writeCapturingChannel.getWrittenObjects();
assertThat(writtenObjects.size(), is(1));
return (FullHttpResponse) writtenObjects.get(0);
}
}
示例7: newNonSslHandler
import io.netty.handler.codec.http.HttpVersion; //導入依賴的package包/類
@Override
protected ChannelHandler newNonSslHandler(ChannelHandlerContext context) {
return new ChannelInboundHandlerAdapter() {
private HttpResponseEncoder encoder = new HttpResponseEncoder();
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
LOG.trace("Received non-SSL request, returning redirect");
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
HttpResponseStatus.MOVED_PERMANENTLY, Unpooled.EMPTY_BUFFER);
response.headers().set(Names.LOCATION, redirectAddress);
LOG.trace(Constants.LOG_RETURNING_RESPONSE, response);
encoder.write(ctx, response, ctx.voidPromise());
ctx.flush();
}
};
}
示例8: testBasicAuthenticationFailure
import io.netty.handler.codec.http.HttpVersion; //導入依賴的package包/類
@Test
public void testBasicAuthenticationFailure() throws Exception {
Configuration config = TestConfiguration.createMinimalConfigurationForTest();
BasicAuthLogin auth = new BasicAuthLogin();
auth.setUsername("test");
auth.setPassword("test2");
DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/login");
request.content().writeBytes(JsonSerializer.getObjectMapper().writeValueAsBytes(auth));
TestHttpQueryDecoder decoder = new TestHttpQueryDecoder(config);
decoder.decode(null, request, results);
Assert.assertEquals(1, results.size());
Object result = results.iterator().next();
Assert.assertEquals(BasicAuthLoginRequest.class, result.getClass());
BasicAuthLoginRequestHandler handler = new BasicAuthLoginRequestHandler(config);
CaptureChannelHandlerContext ctx = new CaptureChannelHandlerContext();
handler.channelRead(ctx, result);
Assert.assertNotNull(ctx.msg);
Assert.assertTrue(ctx.msg instanceof DefaultFullHttpResponse);
DefaultFullHttpResponse response = (DefaultFullHttpResponse) ctx.msg;
Assert.assertEquals(HttpResponseStatus.UNAUTHORIZED, response.getStatus());
Assert.assertTrue(response.headers().contains(Names.CONTENT_TYPE));
Assert.assertEquals(Constants.JSON_TYPE, response.headers().get(Names.CONTENT_TYPE));
}
示例9: handleNonProxyRequest
import io.netty.handler.codec.http.HttpVersion; //導入依賴的package包/類
protected HttpResponse handleNonProxyRequest(FullHttpRequest req) {
String uri = req.getUri();
if ("/version".equals(uri)) {
if (HttpMethod.GET.equals(req.getMethod())) {
JsonObject jsonObj = new JsonObject();
jsonObj.addProperty("name", m_appConfig.getAppName());
jsonObj.addProperty("version", m_appConfig.getAppVersion());
byte[] content = jsonObj.toString().getBytes(CharsetUtil.UTF_8);
DefaultFullHttpResponse resp = new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
Unpooled.copiedBuffer(content));
HttpHeaders.setKeepAlive(resp, false);
HttpHeaders.setHeader(resp, HttpHeaders.Names.CONTENT_TYPE,
"application/json");
HttpHeaders.setContentLength(resp, content.length);
return resp;
}
}
return RESPONSE_404;
}
示例10: testChannelRead0_debugOnResponse
import io.netty.handler.codec.http.HttpVersion; //導入依賴的package包/類
@Test
public void testChannelRead0_debugOnResponse() {
Mockito.when(LOGGER.isDebugEnabled()).thenReturn(true);
Mockito.when(response.getStatus()).thenReturn(HttpResponseStatus.OK);
Mockito.when(response.getProtocolVersion()).thenReturn(HttpVersion.HTTP_1_1);
Mockito.when(headers.isEmpty()).thenReturn(false);
Set<String> headersSet = new HashSet<>();
headersSet.add("no-cache");
Mockito.when(headers.names()).thenReturn(headersSet);
List<String> noCacheValues = new ArrayList<>();
noCacheValues.add("private");
Mockito.when(headers.getAll("no-cache")).thenReturn(noCacheValues);
PowerMockito.mockStatic(HttpHeaders.class);
BDDMockito.given(HttpHeaders.isTransferEncodingChunked(response)).willReturn(true);
handler.channelRead0(ctx, response);
Mockito.verify(LOGGER, Mockito.times(1)).debug("STATUS: " + HttpResponseStatus.OK);
Mockito.verify(LOGGER, Mockito.times(1)).debug("VERSION: " + HttpVersion.HTTP_1_1);
Mockito.verify(LOGGER, Mockito.times(1)).debug("HEADER: no-cache = private");
Mockito.verify(LOGGER, Mockito.times(1)).debug("CHUNKED CONTENT {");
BDDMockito.given(HttpHeaders.isTransferEncodingChunked(response)).willReturn(false);
handler.channelRead0(ctx, response);
Mockito.verify(LOGGER, Mockito.times(1)).debug("CONTENT {");
}
示例11: handleHttpRequest
import io.netty.handler.codec.http.HttpVersion; //導入依賴的package包/類
private void handleHttpRequest(ChannelHandlerContext ctx,
FullHttpRequest req) {
if (!req.getDecoderResult().isSuccess()
|| (!"websocket".equals(req.headers().get("Upgrade")))) {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
return;
}
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
"ws://localhost:7777/websocket", null, false);
socketServerHandshaker = wsFactory.newHandshaker(req);
if (socketServerHandshaker == null) {
WebSocketServerHandshakerFactory
.sendUnsupportedWebSocketVersionResponse(ctx.channel());
} else {
socketServerHandshaker.handshake(ctx.channel(), req);
}
}
示例12: createFullHttpRequest
import io.netty.handler.codec.http.HttpVersion; //導入依賴的package包/類
private FullHttpRequest createFullHttpRequest(HttpHeaders headers) {
io.netty.handler.codec.http.HttpMethod nettyMethod =
io.netty.handler.codec.http.HttpMethod.valueOf(this.method.name());
FullHttpRequest nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
nettyMethod, this.uri.toString(), this.body.buffer());
nettyRequest.headers().set(HttpHeaders.HOST, uri.getHost());
nettyRequest.headers().set(HttpHeaders.CONNECTION, io.netty.handler.codec.http.HttpHeaders.Values.CLOSE);
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
nettyRequest.headers().add(entry.getKey(), entry.getValue());
}
return nettyRequest;
}
示例13: writeAuthenticationRequired
import io.netty.handler.codec.http.HttpVersion; //導入依賴的package包/類
private void writeAuthenticationRequired(String realm) {
String body = "<!DOCTYPE HTML \"-//IETF//DTD HTML 2.0//EN\">\n"
+ "<html><head>\n"
+ "<title>407 Proxy Authentication Required</title>\n"
+ "</head><body>\n"
+ "<h1>Proxy Authentication Required</h1>\n"
+ "<p>This server could not verify that you\n"
+ "are authorized to access the document\n"
+ "requested. Either you supplied the wrong\n"
+ "credentials (e.g., bad password), or your\n"
+ "browser doesn't understand how to supply\n"
+ "the credentials required.</p>\n" + "</body></html>\n";
DefaultFullHttpResponse response = responseFor(HttpVersion.HTTP_1_1,
HttpResponseStatus.PROXY_AUTHENTICATION_REQUIRED, body);
HttpHeaders.setDate(response, new Date());
response.headers().set("Proxy-Authenticate",
"Basic realm=\"" + (realm == null ? "Restricted Files" : realm) + "\"");
write(response);
}
示例14: channelRead0
import io.netty.handler.codec.http.HttpVersion; //導入依賴的package包/類
@Override
protected void channelRead0(ChannelHandlerContext ctx, SuggestRequest msg) throws Exception {
byte[] buf = null;
try {
buf = JsonUtil.getObjectMapper().writeValueAsBytes(dataStore.suggest(msg));
} catch (TimelyException e) {
LOG.error(e.getMessage(), e);
this.sendHttpError(ctx, e);
return;
}
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
Unpooled.copiedBuffer(buf));
response.headers().set(Names.CONTENT_TYPE, Constants.JSON_TYPE);
response.headers().set(Names.CONTENT_LENGTH, response.content().readableBytes());
sendResponse(ctx, response);
}
示例15: channelRead0
import io.netty.handler.codec.http.HttpVersion; //導入依賴的package包/類
@Override
protected void channelRead0(ChannelHandlerContext ctx, SearchLookupRequest msg) throws Exception {
byte[] buf = null;
try {
buf = JsonUtil.getObjectMapper().writeValueAsBytes(dataStore.lookup(msg));
} catch (TimelyException e) {
LOG.error(e.getMessage(), e);
this.sendHttpError(ctx, e);
return;
}
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
Unpooled.copiedBuffer(buf));
response.headers().set(Names.CONTENT_TYPE, Constants.JSON_TYPE);
response.headers().set(Names.CONTENT_LENGTH, response.content().readableBytes());
sendResponse(ctx, response);
}