List of usage examples for io.netty.handler.codec.http HttpMethod POST
HttpMethod POST
To view the source code for io.netty.handler.codec.http HttpMethod POST.
Click Source Link
From source file:HTTPInputTransportTestCase.java
License:Open Source License
public void publishEvent(String event) { try {/*from w w w. j av a 2s . c om*/ HttpURLConnection urlConn = null; try { urlConn = ServerUtil.request(baseURI, "/", HttpMethod.POST.name(), true); } catch (IOException e) { ServerUtil.handleException("IOException occurred while running the HTTPInputTransportTestCase", e); } ServerUtil.writeContent(urlConn, event); assertEquals(200, urlConn.getResponseCode()); String content2 = urlConn.getResponseMessage(); String content = ServerUtil.getContent(urlConn); // urlConn.disconnect(); } catch (IOException e) { ServerUtil.handleException("IOException occurred while running the HTTPInputTransportTestCase", e); } }
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 ww w . j a va 2 s. co m*/ 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// w w w .j av a 2 s . c om */ 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:bzh.ygu.fun.chitchat.HttpChitChatServerHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; if (HttpHeaders.is100ContinueExpected(request)) { send100Continue(ctx);//from ww w . j av a 2s . c o m } String uri = request.uri(); HttpMethod method = request.method(); Root root = Root.getInstance(); buf.setLength(0); contentBuf.setLength(0); if (method == HttpMethod.POST) { if (uri.equals("/chitchat")) { currentAction = "Add"; } } if (method == HttpMethod.GET) { if (uri.startsWith(LATEST)) { latestFromWho = decode(uri.substring(LATEST_SIZE)); currentAction = "Latest"; Message m = root.getLatest(latestFromWho); if (m != null) { //{"author":"Iron Man", "text":"We have a Hulk !", "thread":3,"createdAt":1404736639715} buf.append(m.toJSON()); } } if (uri.startsWith(THREADCALL)) { currentAction = "Thread"; String threadId = uri.substring(THREADCALL_SIZE); MessageThread mt = root.getMessageThread(threadId); if (mt != null) { //{"author":"Iron Man", "text":"We have a Hulk !", "thread":3,"createdAt":1404736639715} buf.append(mt.toJSON()); } } if (uri.startsWith(SEARCH)) { String stringToSearch = decode(uri.substring(SEARCH_SIZE)); currentAction = "search"; List<Message> lm = root.search(stringToSearch); //[{"author":"Loki", "text":"I have an army !", "thread":3, //"createdAt":1404736639710}, {"author":"Iron Man", "text":"We have a Hulk !", // "thread":3, "createdAt":1404736639715}] buf.append("["); if (!lm.isEmpty()) { Iterator<Message> it = lm.iterator(); Message m = it.next(); buf.append(m.toJSON()); while (it.hasNext()) { m = it.next(); buf.append(", "); buf.append(m.toJSON()); } } buf.append("]"); } } } if (msg instanceof HttpContent) { Root root = Root.getInstance(); HttpContent httpContent = (HttpContent) msg; ByteBuf content = httpContent.content(); if (content.isReadable()) { contentBuf.append(content.toString(CharsetUtil.UTF_8)); } if (msg instanceof LastHttpContent) { // buf.append("END OF CONTENT\r\n"); if (currentAction.equals("Add")) { addMessageFromContent(contentBuf.toString(), root); currentAction = "None"; } LastHttpContent trailer = (LastHttpContent) msg; if (!writeResponse(trailer, ctx)) { // If keep-alive is off, close the connection once the content is fully written. ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } } } }
From source file:c5db.control.ClientHttpProtostuffEncoder.java
License:Apache License
@Override protected void encode(ChannelHandlerContext ctx, Message msg, List<Object> out) throws Exception { Class<?> messageType = msg.getClass(); LowCopyProtobufOutput outputSerializer = new LowCopyProtobufOutput(); msg.cachedSchema().writeTo(outputSerializer, msg); List<ByteBuffer> serializedBuffers = outputSerializer.buffer.finish(); ByteBuf requestContent = Unpooled.wrappedBuffer(serializedBuffers.toArray(new ByteBuffer[] {})); DefaultFullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.POST, "foo", requestContent); httpRequest.headers().set(HttpProtostuffConstants.PROTOSTUFF_HEADER_NAME, messageType.getName()); httpRequest.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/octet-stream"); httpRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, requestContent.readableBytes()); out.add(httpRequest);//from w w w . ja va 2 s.co m }
From source file:cc.blynk.core.http.handlers.OTAHandler.java
License:Apache License
@Override public boolean accept(ChannelHandlerContext ctx, HttpRequest req) { if (req.method() == HttpMethod.POST && req.uri().startsWith(handlerUri)) { try {//from w w w . j a v a 2 s. co m User superAdmin = AuthHeadersBaseHttpHandler.validateAuth(userDao, req); if (superAdmin != null) { ctx.channel().attr(AuthHeadersBaseHttpHandler.USER).set(superAdmin); queryStringDecoder = new QueryStringDecoder(req.uri()); return true; } } catch (IllegalAccessException e) { //return 403 and stop processing. ctx.writeAndFlush(Response.forbidden(e.getMessage())); return true; } } return false; }
From source file:cc.blynk.core.http.handlers.UploadHandler.java
License:Apache License
public boolean accept(ChannelHandlerContext ctx, HttpRequest req) { return req.method() == HttpMethod.POST && req.uri().startsWith(handlerUri); }
From source file:ccwihr.client.t1.HttpUploadClient.java
License:Apache License
/** * Standard post without multipart but already support on Factory (memory * management)//w ww . j a v a 2 s . c om * @param se12 * * @return the list of HttpData object (attribute and file) to be reused on * next post */ private static List<InterfaceHttpData> formpost(Bootstrap bootstrap, String host, int port, URI uriSimple, SyncEntity se12, HttpDataFactory factory, List<Entry<String, String>> headers) throws Exception { // XXX /formpost // Start the connection attempt. ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); // Wait until the connection attempt succeeds or fails. Channel channel = future.sync().channel(); // Prepare the HTTP request. HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uriSimple.toASCIIString()); // Use the PostBody encoder HttpPostRequestEncoder bodyRequestEncoder = new HttpPostRequestEncoder(factory, request, false); // false // 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 bodyRequestEncoder.addBodyAttribute("getform", "POST"); bodyRequestEncoder.addBodyAttribute("info", "first value"); bodyRequestEncoder.addBodyAttribute("secondinfo", "secondvalue &"); bodyRequestEncoder.addBodyAttribute("thirdinfo", textArea); bodyRequestEncoder.addBodyAttribute("fourthinfo", textAreaLong); // bodyRequestEncoder.addBodyFileUpload("myfile", file, // "application/x-zip-compressed", false); // finalize request request = bodyRequestEncoder.finalizeRequest(); // 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); } channel.flush(); // 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:cf.service.NettyBrokerServer.java
License:Open Source License
public NettyBrokerServer(SimpleHttpServer server, Provisioner provisioner, String authToken) { super(provisioner, authToken); server.addHandler(Pattern.compile("/+gateway/v1/configurations/(.*?)/handles(/(.*))?"), new RequestHandler() { @Override/*from ww w . jav a 2 s. c o m*/ public HttpResponse handleRequest(HttpRequest request, Matcher uriMatcher, ByteBuf body) throws RequestException { validateAuthToken(request); // Bind service if (request.getMethod() == HttpMethod.POST) { final BindRequest bindRequest = decode(BindRequest.class, body); final BindResponse bindResponse = bindService(bindRequest); return encodeResponse(bindResponse); } // Unbind service if (request.getMethod() == HttpMethod.DELETE) { if (uriMatcher.groupCount() != 3) { throw new RequestException(HttpResponseStatus.NOT_FOUND); } final String serviceInstanceId = uriMatcher.group(1); final String handleId = uriMatcher.group(3); unbindService(serviceInstanceId, handleId); return encodeResponse(EMPTY_JSON_OBJECT); } throw new RequestException(HttpResponseStatus.METHOD_NOT_ALLOWED); } }); server.addHandler(Pattern.compile("/+gateway/v1/configurations(/(.*))?"), new RequestHandler() { @Override public HttpResponse handleRequest(HttpRequest request, Matcher uriMatcher, ByteBuf body) throws RequestException { validateAuthToken(request); // Create service if (request.getMethod() == HttpMethod.POST) { final CreateRequest createRequest = decode(CreateRequest.class, body); final CreateResponse createResponse = createService(createRequest); return encodeResponse(createResponse); } // Delete service if (request.getMethod() == HttpMethod.DELETE) { if (uriMatcher.groupCount() != 2) { throw new RequestException(HttpResponseStatus.NOT_FOUND); } final String serviceInstanceId = uriMatcher.group(2); deleteService(serviceInstanceId); return encodeResponse(EMPTY_JSON_OBJECT); } throw new RequestException(HttpResponseStatus.METHOD_NOT_ALLOWED); } }); }
From source file:cn.wantedonline.puppy.httpserver.component.HttpRequest.java
License:Apache License
public HttpPostRequestDecoder getHttpPostRequestDecoder() { if (!httpPostRequestDecoderInit) { HttpMethod method = getMethod(); if (method.equals(HttpMethod.POST) || method.equals(HttpMethod.PUT)) { try { httpPostRequestDecoder = new HttpPostRequestDecoder(factory, this, charset4ContentDecoder); } catch (HttpPostRequestDecoder.ErrorDataDecoderException e) { log.error("request postDataDecode error:{}", this, e); } catch (HttpPostRequestDecoder.IncompatibleDataDecoderException e) { }/*w w w .j a v a 2s . c o m*/ } httpPostRequestDecoderInit = true; } return httpPostRequestDecoder; }