List of usage examples for io.netty.handler.codec.http HttpVersion HTTP_1_1
HttpVersion HTTP_1_1
To view the source code for io.netty.handler.codec.http HttpVersion HTTP_1_1.
Click Source Link
From source file:HttpUploadServerHandler.java
License:Apache License
private void writeResponse(Channel channel) { // Convert the response content to a ChannelBuffer. ByteBuf buf = copiedBuffer(responseContent.toString(), CharsetUtil.UTF_8); responseContent.setLength(0);//from ww w . j a va 2s . c o m // Decide whether to close the connection or not. boolean close = HttpHeaders.Values.CLOSE.equalsIgnoreCase(request.headers().get(CONNECTION)) || request.getProtocolVersion().equals(HttpVersion.HTTP_1_0) && !HttpHeaders.Values.KEEP_ALIVE.equalsIgnoreCase(request.headers().get(CONNECTION)); // Build the response object. FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf); response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8"); if (!close) { // There's no need to add 'Content-Length' header // if this is the last response. response.headers().set(CONTENT_LENGTH, String.valueOf(buf.readableBytes())); } Set<Cookie> cookies; String value = request.headers().get(COOKIE); if (value == null) { cookies = Collections.emptySet(); } else { cookies = CookieDecoder.decode(value); } if (!cookies.isEmpty()) { // Reset the cookies if necessary. for (Cookie cookie : cookies) { response.headers().add(SET_COOKIE, ServerCookieEncoder.encode(cookie)); } } // Write the response. ChannelFuture future = channel.write(response); // Close the connection after the write operation is done if necessary. if (close) { future.addListener(ChannelFutureListener.CLOSE); } }
From source file:HttpUploadServerHandler.java
License:Apache License
private void writeMenu(ChannelHandlerContext ctx) { // print several HTML forms // Convert the response content to a ChannelBuffer. responseContent.setLength(0);//from w w w. j a v a 2s .co m // create Pseudo Menu responseContent.append("<html>"); responseContent.append("<head>"); responseContent.append("<title>Netty Test Form</title>\r\n"); responseContent.append("</head>\r\n"); responseContent.append("<body bgcolor=white><style>td{font-size: 12pt;}</style>"); responseContent.append("<table border=\"0\">"); responseContent.append("<tr>"); responseContent.append("<td>"); responseContent.append("<h1>Netty Test Form</h1>"); responseContent.append("Choose one FORM"); responseContent.append("</td>"); responseContent.append("</tr>"); responseContent.append("</table>\r\n"); // GET responseContent.append("<CENTER>GET FORM<HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>"); responseContent.append("<FORM ACTION=\"/formget\" METHOD=\"GET\">"); responseContent.append("<input type=hidden name=getform value=\"GET\">"); responseContent.append("<table border=\"0\">"); responseContent.append("<tr><td>Fill with value: <br> <input type=text name=\"info\" size=10></td></tr>"); responseContent.append("<tr><td>Fill with value: <br> <input type=text name=\"secondinfo\" size=20>"); responseContent .append("<tr><td>Fill with value: <br> <textarea name=\"thirdinfo\" cols=40 rows=10></textarea>"); responseContent.append("</td></tr>"); responseContent.append("<tr><td><INPUT TYPE=\"submit\" NAME=\"Send\" VALUE=\"Send\"></INPUT></td>"); responseContent.append("<td><INPUT TYPE=\"reset\" NAME=\"Clear\" VALUE=\"Clear\" ></INPUT></td></tr>"); responseContent.append("</table></FORM>\r\n"); responseContent.append("<CENTER><HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>"); // POST responseContent.append("<CENTER>POST FORM<HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>"); responseContent.append("<FORM ACTION=\"/formpost\" METHOD=\"POST\">"); responseContent.append("<input type=hidden name=getform value=\"POST\">"); responseContent.append("<table border=\"0\">"); responseContent.append("<tr><td>Fill with value: <br> <input type=text name=\"info\" size=10></td></tr>"); responseContent.append("<tr><td>Fill with value: <br> <input type=text name=\"secondinfo\" size=20>"); responseContent .append("<tr><td>Fill with value: <br> <textarea name=\"thirdinfo\" cols=40 rows=10></textarea>"); responseContent.append("<tr><td>Fill with file (only file name will be transmitted): <br> " + "<input type=file name=\"myfile\">"); responseContent.append("</td></tr>"); responseContent.append("<tr><td><INPUT TYPE=\"submit\" NAME=\"Send\" VALUE=\"Send\"></INPUT></td>"); responseContent.append("<td><INPUT TYPE=\"reset\" NAME=\"Clear\" VALUE=\"Clear\" ></INPUT></td></tr>"); responseContent.append("</table></FORM>\r\n"); responseContent.append("<CENTER><HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>"); // POST with enctype="multipart/form-data" responseContent.append("<CENTER>POST MULTIPART FORM<HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>"); responseContent .append("<FORM ACTION=\"/formpostmultipart\" ENCTYPE=\"multipart/form-data\" METHOD=\"POST\">"); responseContent.append("<input type=hidden name=getform value=\"POST\">"); responseContent.append("<table border=\"0\">"); responseContent.append("<tr><td>Fill with value: <br> <input type=text name=\"info\" size=10></td></tr>"); responseContent.append("<tr><td>Fill with value: <br> <input type=text name=\"secondinfo\" size=20>"); responseContent .append("<tr><td>Fill with value: <br> <textarea name=\"thirdinfo\" cols=40 rows=10></textarea>"); responseContent.append("<tr><td>Fill with file: <br> <input type=file name=\"myfile\">"); responseContent.append("</td></tr>"); responseContent.append("<tr><td><INPUT TYPE=\"submit\" NAME=\"Send\" VALUE=\"Send\"></INPUT></td>"); responseContent.append("<td><INPUT TYPE=\"reset\" NAME=\"Clear\" VALUE=\"Clear\" ></INPUT></td></tr>"); responseContent.append("</table></FORM>\r\n"); responseContent.append("<CENTER><HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>"); responseContent.append("</body>"); responseContent.append("</html>"); ByteBuf buf = copiedBuffer(responseContent.toString(), CharsetUtil.UTF_8); // Build the response object. FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf); response.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8"); response.headers().set(CONTENT_LENGTH, String.valueOf(buf.readableBytes())); // Write the response. ctx.channel().write(response); }
From source file:HttpUploadClient.java
License:Apache License
/** * Standard usage of HTTP API in Netty without file Upload (get is not able to achieve File upload due to limitation * on request size)./*from w w w.j a va2 s .c om*/ * * @return the list of headers that will be used in every example after **/ private static List<Entry<String, String>> formGet(Bootstrap bootstrap, String host, int port, String get, URI uriSimple) throws Exception { // Start the connection attempt. // No use of HttpPostRequestEncoder since not a POST Channel channel = bootstrap.connect(host, port).sync().channel(); // Prepare the HTTP request. QueryStringEncoder encoder = new QueryStringEncoder(get); // add Form attribute encoder.addParam("getform", "GET"); encoder.addParam("info", "first value"); encoder.addParam("secondinfo", "secondvalue &"); // not the big one since it is not compatible with GET size // encoder.addParam("thirdinfo", textArea); encoder.addParam("thirdinfo", "third value\r\ntest second line\r\n\r\nnew line\r\n"); encoder.addParam("Send", "Send"); URI uriGet; try { uriGet = new URI(encoder.toString()); } catch (URISyntaxException e) { logger.log(Level.WARNING, "Error: ", e); return null; } FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uriGet.toASCIIString()); HttpHeaders headers = request.headers(); headers.set(HttpHeaders.Names.HOST, host); headers.set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); headers.set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP + ',' + HttpHeaders.Values.DEFLATE); headers.set(HttpHeaders.Names.ACCEPT_CHARSET, "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); headers.set(HttpHeaders.Names.ACCEPT_LANGUAGE, "fr"); headers.set(HttpHeaders.Names.REFERER, uriSimple.toString()); headers.set(HttpHeaders.Names.USER_AGENT, "Netty Simple Http Client side"); headers.set(HttpHeaders.Names.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); headers.set(HttpHeaders.Names.COOKIE, ClientCookieEncoder.encode(new DefaultCookie("my-cookie", "foo"), new DefaultCookie("another-cookie", "bar"))); // send request List<Entry<String, String>> entries = headers.entries(); channel.write(request).sync(); // Wait for the server to close the connection. channel.closeFuture().sync(); return entries; }
From source file:HttpUploadClient.java
License:Apache License
/** * Standard post without multipart but already support on Factory (memory management) * * @return the list of HttpData object (attribute and file) to be reused on next post *///from w w w. j a v a 2s . c om private static List<InterfaceHttpData> formPost(Bootstrap bootstrap, String host, int port, URI uriSimple, File file, HttpDataFactory factory, List<Entry<String, String>> headers) throws Exception { // Start the connection attempt Channel channel = bootstrap.connect(host, port).sync().channel(); // Prepare the HTTP request. HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uriSimple.toASCIIString()); // Use the PostBody encoder HttpPostRequestEncoder bodyRequestEncoder = null; try { bodyRequestEncoder = new HttpPostRequestEncoder(factory, request, false); // false not multipart } catch (NullPointerException e) { // should not be since args are not null e.printStackTrace(); } catch (ErrorDataEncoderException e) { // test if getMethod is a POST getMethod e.printStackTrace(); } // it is legal to add directly header or cookie into the request until finalize for (Entry<String, String> entry : headers) { request.headers().set(entry.getKey(), entry.getValue()); } // add Form attribute try { bodyRequestEncoder.addBodyAttribute("getform", "POST"); bodyRequestEncoder.addBodyAttribute("info", "first value"); bodyRequestEncoder.addBodyAttribute("secondinfo", "secondvalue &"); bodyRequestEncoder.addBodyAttribute("thirdinfo", textArea); bodyRequestEncoder.addBodyFileUpload("myfile", file, "application/x-zip-compressed", false); bodyRequestEncoder.addBodyAttribute("Send", "Send"); } catch (NullPointerException e) { // should not be since not null args e.printStackTrace(); } catch (ErrorDataEncoderException e) { // if an encoding error occurs e.printStackTrace(); } // finalize request try { request = bodyRequestEncoder.finalizeRequest(); } catch (ErrorDataEncoderException e) { // if an encoding error occurs e.printStackTrace(); } // Create the bodylist to be reused on the last version with Multipart support List<InterfaceHttpData> bodylist = bodyRequestEncoder.getBodyListAttributes(); // send request channel.write(request); // test if request was chunked and if so, finish the write if (bodyRequestEncoder.isChunked()) { // could do either request.isChunked() // either do it through ChunkedWriteHandler channel.write(bodyRequestEncoder).awaitUninterruptibly(); } // Do not clear here since we will reuse the InterfaceHttpData on the // next request // for the example (limit action on client side). Take this as a // broadcast of the same // request on both Post actions. // // On standard program, it is clearly recommended to clean all files // after each request // bodyRequestEncoder.cleanFiles(); // Wait for the server to close the connection. channel.closeFuture().sync(); return bodylist; }
From source file:HttpUploadClient.java
License:Apache License
/** * Multipart example/*from ww w.ja va 2 s. co m*/ */ private static void formPostMultipart(Bootstrap bootstrap, String host, int port, URI uriFile, HttpDataFactory factory, List<Entry<String, String>> headers, List<InterfaceHttpData> bodylist) throws Exception { // Start the connection attempt Channel channel = bootstrap.connect(host, port).sync().channel(); // Prepare the HTTP request. HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uriFile.toASCIIString()); // Use the PostBody encoder HttpPostRequestEncoder bodyRequestEncoder = null; try { bodyRequestEncoder = new HttpPostRequestEncoder(factory, request, true); // true => multipart } catch (NullPointerException e) { // should not be since no null args e.printStackTrace(); } catch (ErrorDataEncoderException e) { // test if getMethod is a POST getMethod e.printStackTrace(); } // it is legal to add directly header or cookie into the request until finalize for (Entry<String, String> entry : headers) { request.headers().set(entry.getKey(), entry.getValue()); } // add Form attribute from previous request in formpost() try { bodyRequestEncoder.setBodyHttpDatas(bodylist); } catch (NullPointerException e1) { // should not be since previously created e1.printStackTrace(); } catch (ErrorDataEncoderException e1) { // again should not be since previously encoded (except if an error // occurs previously) e1.printStackTrace(); } // finalize request try { request = bodyRequestEncoder.finalizeRequest(); } catch (ErrorDataEncoderException e) { // if an encoding error occurs e.printStackTrace(); } // send request channel.write(request); // test if request was chunked and if so, finish the write if (bodyRequestEncoder.isChunked()) { channel.write(bodyRequestEncoder).awaitUninterruptibly(); } // Now no more use of file representation (and list of HttpData) bodyRequestEncoder.cleanFiles(); // Wait for the server to close the connection. channel.closeFuture().sync(); }
From source file:br.unifei.edu.eco009.steamlansync.cache.HttpChunkContents.java
public FullHttpResponse getFullHttpResponse() { DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.copiedBuffer(bytes)); HttpHeaders head = response.headers(); for (Entry<String, String> entry : headers.entrySet()) { head.add(entry.getKey(), entry.getValue()); }/* w ww. jav a 2s . com*/ return response; }
From source file:br.unifei.edu.eco009.steamlansync.proxy.HttpResponseContent.java
public FullHttpResponse getFullResponse() { ByteBuf buffer = Unpooled.copiedBuffer(bytes); FullHttpResponse newResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buffer);/*from ww w.ja v a 2 s. com*/ if (length != null) newResponse.headers().add("Content-Length", length); if (steam_sid != null) newResponse.headers().add("x-steam-sid", steam_sid); if (crc != null) newResponse.headers().add("x-content-crc", crc); newResponse.headers().add("content-type", "application/x-steam-chunk"); return newResponse.retain(); }
From source file:catacumba.websocket.internal.WebSocketEngine.java
License:Apache License
@SuppressWarnings("deprecation") public static <T> void connect(final Context context, String path, int maxLength, final WebSocketHandler<T> handler) { PublicAddress publicAddress = context.get(PublicAddress.class); URI address = publicAddress.get(context); URI httpPath = address.resolve(path); URI wsPath;// ww w . ja v a2 s . co m try { wsPath = new URI("ws", httpPath.getUserInfo(), httpPath.getHost(), httpPath.getPort(), httpPath.getPath(), httpPath.getQuery(), httpPath.getFragment()); } catch (URISyntaxException e) { throw uncheck(e); } WebSocketServerHandshakerFactory factory = new WebSocketServerHandshakerFactory(wsPath.toString(), null, true, maxLength); Request request = context.getRequest(); HttpMethod method = valueOf(request.getMethod().getName()); FullHttpRequest nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, method, request.getUri()); nettyRequest.headers().add(SEC_WEBSOCKET_VERSION, request.getHeaders().get(SEC_WEBSOCKET_VERSION)); nettyRequest.headers().add(SEC_WEBSOCKET_KEY, request.getHeaders().get(SEC_WEBSOCKET_KEY)); final WebSocketServerHandshaker handshaker = factory.newHandshaker(nettyRequest); final DirectChannelAccess directChannelAccess = context.getDirectChannelAccess(); final Channel channel = directChannelAccess.getChannel(); if (!channel.config().isAutoRead()) { channel.config().setAutoRead(true); } handshaker.handshake(channel, nettyRequest) .addListener(new HandshakeFutureListener<>(context, handshaker, handler)); }
From source file:cc.changic.platform.etl.schedule.http.HttpHeaderUtil.java
License:Apache License
/** * Returns {@code true} if and only if the specified message contains the * {@code "Expect: 100-continue"} header. *//*from w w w. ja v a2s . c om*/ public static boolean is100ContinueExpected(HttpMessage message) { // Expect: 100-continue is for requests only. if (!(message instanceof HttpRequest)) { return false; } // It works only on HTTP/1.1 or later. if (message.protocolVersion().compareTo(HttpVersion.HTTP_1_1) < 0) { return false; } // In most cases, there will be one or zero 'Expect' header. String value = message.headers().get(Names.EXPECT); if (value == null) { return false; } if (AsciiString.equalsIgnoreCase(Values.CONTINUE, value)) { return true; } // Multiple 'Expect' headers. Search through them. return message.headers().contains(Names.EXPECT, Values.CONTINUE, true); }
From source file:cc.io.lessons.server.HttpUploadServerHandler.java
License:Apache License
private void writeResponse(Channel channel) { // Convert the response content to a ChannelBuffer. ByteBuf buf = copiedBuffer(responseContent.toString(), CharsetUtil.UTF_8); responseContent.setLength(0);/*from www . j a va2 s . c o m*/ // Decide whether to close the connection or not. boolean close = HttpHeaders.Values.CLOSE.equalsIgnoreCase(request.headers().get(CONNECTION)) || request.getProtocolVersion().equals(HttpVersion.HTTP_1_0) && !HttpHeaders.Values.KEEP_ALIVE.equalsIgnoreCase(request.headers().get(CONNECTION)); // Build the response object. FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf); response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8"); if (!close) { // There's no need to add 'Content-Length' header // if this is the last response. response.headers().set(CONTENT_LENGTH, buf.readableBytes()); } Set<Cookie> cookies; String value = request.headers().get(COOKIE); if (value == null) { cookies = Collections.emptySet(); } else { cookies = CookieDecoder.decode(value); } if (!cookies.isEmpty()) { // Reset the cookies if necessary. for (Cookie cookie : cookies) { response.headers().add(SET_COOKIE, ServerCookieEncoder.encode(cookie)); } } // Write the response. ChannelFuture future = channel.writeAndFlush(response); // Close the connection after the write operation is done if necessary. if (close) { future.addListener(ChannelFutureListener.CLOSE); } }