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:cn.wcl.test.netty.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 av a 2 s . 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 { // 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 => not multipart // 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:cn.wcl.test.netty.HttpUploadClient.java
License:Apache License
/** * Multipart example/* ww w . j a v a 2 s . co m*/ */ private static void formpostmultipart(Bootstrap bootstrap, String host, int port, URI uriFile, HttpDataFactory factory, Iterable<Entry<String, String>> headers, List<InterfaceHttpData> bodylist) throws Exception { // XXX /formpostmultipart // 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, uriFile.toASCIIString()); // Use the PostBody encoder HttpPostRequestEncoder bodyRequestEncoder = new HttpPostRequestEncoder(factory, request, true); // true => multipart // 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() bodyRequestEncoder.setBodyHttpDatas(bodylist); // finalize request bodyRequestEncoder.finalizeRequest(); // send request channel.write(request); // test if request was chunked and if so, finish the write if (bodyRequestEncoder.isChunked()) { channel.write(bodyRequestEncoder); } channel.flush(); // 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:cn.zyf.handler.ObjectStorageHandler.java
License:Open Source License
@Override protected void channelRead0(ChannelHandlerContext ctx, RequestInfo requestInfo) throws Exception { if (isListBuckets(requestInfo) || (requestInfo.getVerb() != HttpMethod.POST && !requestInfo.getBucketName().equals("") && requestInfo.getObjectName().equals(""))) { LOG.info("start process requestID=" + requestInfo.getId() + " with bucketProcessor"); bucketProcessor(requestInfo);/*from ww w.j a v a 2 s.com*/ } else { LOG.info("start process requestID=" + requestInfo.getId() + " with objectProcessor"); objectProcessor(requestInfo); } }
From source file:co.rsk.rpc.netty.Web3HttpMethodFilterHandler.java
License:Open Source License
@Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) { HttpMethod httpMethod = request.getMethod(); if (HttpMethod.POST.equals(httpMethod)) { // retain the request so it isn't released automatically by SimpleChannelInboundHandler ctx.fireChannelRead(request.retain()); } else {//from w w w. j a v a 2 s .co m HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_IMPLEMENTED); ctx.write(response).addListener(ChannelFutureListener.CLOSE); } }
From source file:com.addthis.hydra.query.web.HttpQueryHandler.java
License:Apache License
protected void messageReceived(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { if (!request.getDecoderResult().isSuccess()) { sendError(ctx, HttpResponseStatus.BAD_REQUEST); return;/*from w w w .j av a 2 s . c om*/ } QueryStringDecoder urlDecoder = new QueryStringDecoder(request.getUri()); String target = urlDecoder.path(); if (request.getMethod() == HttpMethod.POST) { log.trace("POST Method handling triggered for {}", request); String postBody = request.content().toString(CharsetUtil.UTF_8); log.trace("POST body {}", postBody); urlDecoder = new QueryStringDecoder(postBody, false); } log.trace("target uri {}", target); KVPairs kv = new KVPairs(); /** * The "/query/google/submit" endpoint needs to unpack the * "state" parameter into KV pairs. */ if (target.equals("/query/google/submit")) { String state = urlDecoder.parameters().get("state").get(0); QueryStringDecoder newDecoder = new QueryStringDecoder(state, false); decodeParameters(newDecoder, kv); if (urlDecoder.parameters().containsKey("code")) { kv.add(GoogleDriveAuthentication.authtoken, urlDecoder.parameters().get("code").get(0)); } if (urlDecoder.parameters().containsKey("error")) { kv.add(GoogleDriveAuthentication.autherror, urlDecoder.parameters().get("error").get(0)); } } else { decodeParameters(urlDecoder, kv); } log.trace("kv pairs {}", kv); switch (target) { case "/": sendRedirect(ctx, "/query/index.html"); break; case "/q/": sendRedirect(ctx, "/query/call?" + kv.toString()); break; case "/query/call": case "/query/call/": QueryServer.rawQueryCalls.inc(); queryQueue.queueQuery(meshQueryMaster, kv, request, ctx); break; case "/query/google/authorization": GoogleDriveAuthentication.gdriveAuthorization(kv, ctx); break; case "/query/google/submit": boolean success = GoogleDriveAuthentication.gdriveAccessToken(kv, ctx); if (success) { queryQueue.queueQuery(meshQueryMaster, kv, request, ctx); } break; default: fastHandle(ctx, request, target, kv); break; } }
From source file:com.ahanda.techops.noty.clientTest.ClientHandler.java
License:Apache License
private void getEvents(Channel ch, FullHttpResponse resp) { StringWriter estr = new StringWriter(); getEvents.write(estr);/*from w ww . java2 s .c o m*/ String contentStr = estr.toString(); FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/events/get", ch.alloc().buffer().writeBytes(contentStr.getBytes())); request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); request.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/json"); request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, request.content().readableBytes()); // Set some example cookies. request.headers().set(HttpHeaders.Names.COOKIE, ClientCookieEncoder.encode(sessCookies)); l.info("getevents bytes {}", request.content().readableBytes()); // Send the HTTP request. ch.writeAndFlush(request); }
From source file:com.ahanda.techops.noty.clientTest.ClientHandler.java
License:Apache License
public void login(Channel ch, JSONObject credential) { StringWriter estr = new StringWriter(); credential.write(estr);// w ww . jav a2 s. c o m String contentStr = estr.toString(); FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/login", ch.alloc().buffer().writeBytes(contentStr.getBytes())); request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); request.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/json"); if (sessCookies != null) request.headers().set(HttpHeaders.Names.COOKIE, ClientCookieEncoder.encode(sessCookies)); request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, request.content().readableBytes()); l.info("login request {}", request); // Send the HTTP request. ch.writeAndFlush(request); }
From source file:com.ahanda.techops.noty.clientTest.ClientHandler.java
License:Apache License
public void pubEvent(Channel ch, JSONObject e, FullHttpResponse resp) { // Prepare the HTTP request. JSONArray es = new JSONArray(); es.put(e);/*from w w w . j av a 2 s. co m*/ StringWriter estr = new StringWriter(); es.write(estr); String contentStr = estr.toString(); FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/events", ch.alloc().buffer().writeBytes(contentStr.getBytes())); request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); request.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/json"); request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, request.content().readableBytes()); // Set some example cookies. request.headers().set(HttpHeaders.Names.COOKIE, ClientCookieEncoder.encode(sessCookies)); l.info("PUB Event request {}", request); // Send the HTTP request. ch.writeAndFlush(request); }
From source file:com.alibaba.dubbo.qos.command.decoder.HttpCommandDecoder.java
License:Apache License
public static CommandContext decode(HttpRequest request) { CommandContext commandContext = null; if (request != null) { QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri()); String path = queryStringDecoder.path(); String[] array = path.split("/"); if (array.length == 2) { String name = array[1]; // process GET request and POST request separately. Check url for GET, and check body for POST if (request.getMethod() == HttpMethod.GET) { if (queryStringDecoder.parameters().isEmpty()) { commandContext = CommandContextFactory.newInstance(name); commandContext.setHttp(true); } else { List<String> valueList = new ArrayList<String>(); for (List<String> values : queryStringDecoder.parameters().values()) { valueList.addAll(values); }/*ww w. ja v a2 s . co m*/ commandContext = CommandContextFactory.newInstance(name, valueList.toArray(new String[] {}), true); } } else if (request.getMethod() == HttpMethod.POST) { HttpPostRequestDecoder httpPostRequestDecoder = new HttpPostRequestDecoder(request); List<String> valueList = new ArrayList<String>(); for (InterfaceHttpData interfaceHttpData : httpPostRequestDecoder.getBodyHttpDatas()) { if (interfaceHttpData.getHttpDataType() == InterfaceHttpData.HttpDataType.Attribute) { Attribute attribute = (Attribute) interfaceHttpData; try { valueList.add(attribute.getValue()); } catch (IOException ex) { throw new RuntimeException(ex); } } } if (valueList.isEmpty()) { commandContext = CommandContextFactory.newInstance(name); commandContext.setHttp(true); } else { commandContext = CommandContextFactory.newInstance(name, valueList.toArray(new String[] {}), true); } } } } return commandContext; }
From source file:com.andrewkroh.cisco.xmlservices.DefaultXmlPushService.java
License:Apache License
/** * Builds a HTTP POST request containing the marshaled CiscoIPPhoneExecute * object in the body.//from w ww . j a v a 2 s .co m * * <p/> * The phones require authentication in order to execute the commands. The * specified {@code username} and {@code password} will be included in the * request using HTTP Basic Authentication. * * @param hostname * hostname of the server where the request will be sent * @param username * username for authentiation to the phone * @param password * password for authentication to the phone * @param command * command to execute, this will be marshaled to XML * @param baseCallbackUrl * optional base URL to the callback resource, any URLs in the * outgoing command will have $BASEURL replaced with this value. * {@code callbackUrl} cannot not end with '/'. * @return a fully-populated HTTP request */ private static HttpRequest buildRequest(String hostname, String username, String password, CiscoIPPhoneExecute command, String baseCallbackUrl) { Preconditions.checkNotNull(username, "Username cannot be null."); Preconditions.checkNotNull(password, "Password cannot be null."); Preconditions.checkNotNull(command, "CiscoIPPhoneExecute object cannot be null."); if (baseCallbackUrl != null) { replaceBaseUrlPlaceholder(command, baseCallbackUrl); } // Marshal object to XML and escape the XML: String objectAsXml = XmlMarshaller.marshalToXml(command); String urlEncodedXml = urlEncode(objectAsXml); // Build the content of the POST body: StringBuilder postContent = new StringBuilder(); postContent.append("XML="); postContent.append(urlEncodedXml); // Encode the POST body to bytes: byte[] encodedPostContent = postContent.toString().getBytes(ENCODING); ByteBuf postContentByteBuf = Unpooled.wrappedBuffer(encodedPostContent); // Encode credentials: String encodedCredentials = base64EncodeCredentials(username, password); // Build the HTTP request: FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, CISCO_CGI_EXECUTE_PATH, postContentByteBuf); request.headers().set(HttpHeaders.Names.HOST, hostname); request.headers().set(HttpHeaders.Names.AUTHORIZATION, encodedCredentials); request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); request.headers().set(HttpHeaders.Names.CONTENT_TYPE, HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED); request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, encodedPostContent.length); return request; }