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:net.oebs.jalos.netty.HttpHandler.java
License:Open Source License
private FullHttpResponse handleRequest(HttpRequest request) { FullHttpResponse response = null;// www .j av a 2 s .c o m String uri = request.getUri(); // lookup Handler class by URL Class cls = null; for (Route route : routes) { if (uri.matches(route.path)) { cls = route.handler; break; } } // no matching handler == 404 if (cls == null) { log.info("No handler match found for uri {}", uri); return notFound(); } Handler h; try { h = (Handler) cls.newInstance(); } catch (InstantiationException | IllegalAccessException ex) { return internalError(); } Map<String, String> params = null; HttpMethod method = request.getMethod(); // dispatch based on request method try { if (method.equals(HttpMethod.POST)) { HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(false), request); params = httpDataToStringMap(decoder.getBodyHttpDatas()); response = h.handlePost(uri, params); } else if (method.equals(HttpMethod.GET)) { params = new HashMap<>(); response = h.handleGet(uri, params); } else { response = badRequest(); } } catch (BadRequest ex) { response = badRequest(); } catch (NotFound ex) { response = notFound(); } catch (HandlerError ex) { response = internalError(); } return response; }
From source file:org.apache.activemq.artemis.core.remoting.impl.netty.HttpAcceptorHandler.java
License:Apache License
@Override public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception { FullHttpRequest request = (FullHttpRequest) msg; HttpMethod method = request.getMethod(); // if we are a post then we send upstream, otherwise we are just being prompted for a response. if (method.equals(HttpMethod.POST)) { ctx.fireChannelRead(ReferenceCountUtil.retain(((FullHttpRequest) msg).content())); // add a new response responses.put(new ResponseHolder(System.currentTimeMillis() + responseTime, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK))); ReferenceCountUtil.release(msg); return;//from ww w . j av a2s . co m } super.channelRead(ctx, msg); }
From source file:org.apache.asterix.api.http.server.RestApiServlet.java
License:Apache License
private String query(IServletRequest request) { if (request.getHttpRequest().method() == HttpMethod.POST) { return HttpUtil.getRequestBody(request); } else {//w w w.j ava2 s . c om return getQueryParameter(request); } }
From source file:org.apache.camel.component.netty4.http.DefaultNettyHttpBinding.java
License:Apache License
@Override public HttpRequest toNettyRequest(Message message, String uri, NettyHttpConfiguration configuration) throws Exception { LOG.trace("toNettyRequest: {}", message); // the message body may already be a Netty HTTP response if (message.getBody() instanceof HttpRequest) { return (HttpRequest) message.getBody(); }//from w w w . j a va 2 s. c om // just assume GET for now, we will later change that to the actual method to use HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri); Object body = message.getBody(); if (body != null) { // support bodies as native Netty ByteBuf buffer; if (body instanceof ByteBuf) { buffer = (ByteBuf) body; } else { // try to convert to buffer first buffer = message.getBody(ByteBuf.class); if (buffer == null) { // fallback to byte array as last resort byte[] data = message.getMandatoryBody(byte[].class); buffer = NettyConverter.toByteBuffer(data); } } if (buffer != null) { request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uri, buffer); int len = buffer.readableBytes(); // set content-length request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, len); LOG.trace("Content-Length: {}", len); } else { // we do not support this kind of body throw new NoTypeConversionAvailableException(body, ByteBuf.class); } } // update HTTP method accordingly as we know if we have a body or not HttpMethod method = NettyHttpHelper.createMethod(message, body != null); request.setMethod(method); TypeConverter tc = message.getExchange().getContext().getTypeConverter(); // if we bridge endpoint then we need to skip matching headers with the HTTP_QUERY to avoid sending // duplicated headers to the receiver, so use this skipRequestHeaders as the list of headers to skip Map<String, Object> skipRequestHeaders = null; if (configuration.isBridgeEndpoint()) { String queryString = message.getHeader(Exchange.HTTP_QUERY, String.class); if (queryString != null) { skipRequestHeaders = URISupport.parseQuery(queryString, false, true); } // Need to remove the Host key as it should be not used message.getHeaders().remove("host"); } // append headers // must use entrySet to ensure case of keys is preserved for (Map.Entry<String, Object> entry : message.getHeaders().entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); // we should not add headers for the parameters in the uri if we bridge the endpoint // as then we would duplicate headers on both the endpoint uri, and in HTTP headers as well if (skipRequestHeaders != null && skipRequestHeaders.containsKey(key)) { continue; } // use an iterator as there can be multiple values. (must not use a delimiter) final Iterator<?> it = ObjectHelper.createIterator(value, null, true); while (it.hasNext()) { String headerValue = tc.convertTo(String.class, it.next()); if (headerValue != null && headerFilterStrategy != null && !headerFilterStrategy .applyFilterToCamelHeaders(key, headerValue, message.getExchange())) { LOG.trace("HTTP-Header: {}={}", key, headerValue); request.headers().add(key, headerValue); } } } // set the content type in the response. String contentType = MessageHelper.getContentType(message); if (contentType != null) { // set content-type request.headers().set(HttpHeaders.Names.CONTENT_TYPE, contentType); LOG.trace("Content-Type: {}", contentType); } // must include HOST header as required by HTTP 1.1 // use URI as its faster than URL (no DNS lookup) URI u = new URI(uri); String host = u.getHost(); request.headers().set(HttpHeaders.Names.HOST, host); LOG.trace("Host: {}", host); // configure connection to accordingly to keep alive configuration // favor using the header from the message String connection = message.getHeader(HttpHeaders.Names.CONNECTION, String.class); if (connection == null) { // fallback and use the keep alive from the configuration if (configuration.isKeepAlive()) { connection = HttpHeaders.Values.KEEP_ALIVE; } else { connection = HttpHeaders.Values.CLOSE; } } request.headers().set(HttpHeaders.Names.CONNECTION, connection); LOG.trace("Connection: {}", connection); return request; }
From source file:org.apache.camel.component.netty4.http.NettyHttpHelper.java
License:Apache License
/** * Creates the {@link HttpMethod} to use to call the remote server, often either its GET or POST. * * @param message the Camel message/*w ww. ja va 2 s. c o m*/ * @return the created method */ public static HttpMethod createMethod(Message message, boolean hasPayload) { // use header first HttpMethod m = message.getHeader(Exchange.HTTP_METHOD, HttpMethod.class); if (m != null) { return m; } String name = message.getHeader(Exchange.HTTP_METHOD, String.class); if (name != null) { return HttpMethod.valueOf(name); } if (hasPayload) { // use POST if we have payload return HttpMethod.POST; } else { // fallback to GET return HttpMethod.GET; } }
From source file:org.apache.dubbo.qos.command.decoder.HttpCommandDecoderTest.java
License:Apache License
@Test public void decodePost() throws Exception { FullHttpRequest request = mock(FullHttpRequest.class); when(request.getUri()).thenReturn("localhost:80/test"); when(request.getMethod()).thenReturn(HttpMethod.POST); when(request.headers()).thenReturn(HttpHeaders.EMPTY_HEADERS); ByteBuf buf = Unpooled.copiedBuffer("a=b&c=d", StandardCharsets.UTF_8); when(request.content()).thenReturn(buf); CommandContext context = HttpCommandDecoder.decode(request); assertThat(context.getCommandName(), equalTo("test")); assertThat(context.isHttp(), is(true)); assertThat(context.getArgs(), arrayContaining("b", "d")); }
From source file:org.apache.flink.runtime.webmonitor.HttpRequestHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) { try {/* w w w . j a va2 s. com*/ if (msg instanceof HttpRequest) { currentRequest = (HttpRequest) msg; currentRequestPath = null; if (currentDecoder != null) { currentDecoder.destroy(); currentDecoder = null; } if (currentRequest.getMethod() == HttpMethod.GET || currentRequest.getMethod() == HttpMethod.DELETE) { // directly delegate to the router ctx.fireChannelRead(currentRequest); } else if (currentRequest.getMethod() == HttpMethod.POST) { // POST comes in multiple objects. First the request, then the contents // keep the request and path for the remaining objects of the POST request currentRequestPath = new QueryStringDecoder(currentRequest.getUri()).path(); currentDecoder = new HttpPostRequestDecoder(DATA_FACTORY, currentRequest); } else { throw new IOException("Unsupported HTTP method: " + currentRequest.getMethod().name()); } } else if (currentDecoder != null && msg instanceof HttpContent) { // received new chunk, give it to the current decoder HttpContent chunk = (HttpContent) msg; currentDecoder.offer(chunk); try { while (currentDecoder.hasNext()) { InterfaceHttpData data = currentDecoder.next(); // IF SOMETHING EVER NEEDS POST PARAMETERS, THIS WILL BE THE PLACE TO HANDLE IT // all fields values will be passed with type Attribute. if (data.getHttpDataType() == HttpDataType.FileUpload) { DiskFileUpload file = (DiskFileUpload) data; if (file.isCompleted()) { String name = file.getFilename(); File target = new File(tmpDir, UUID.randomUUID() + "_" + name); file.renameTo(target); QueryStringEncoder encoder = new QueryStringEncoder(currentRequestPath); encoder.addParam("filepath", target.getAbsolutePath()); encoder.addParam("filename", name); currentRequest.setUri(encoder.toString()); } } data.release(); } } catch (EndOfDataDecoderException ignored) { } if (chunk instanceof LastHttpContent) { HttpRequest request = currentRequest; currentRequest = null; currentRequestPath = null; currentDecoder.destroy(); currentDecoder = null; // fire next channel handler ctx.fireChannelRead(request); } } } catch (Throwable t) { currentRequest = null; currentRequestPath = null; if (currentDecoder != null) { currentDecoder.destroy(); currentDecoder = null; } if (ctx.channel().isActive()) { byte[] bytes = ExceptionUtils.stringifyException(t).getBytes(ENCODING); DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR, Unpooled.wrappedBuffer(bytes)); response.headers().set(HttpHeaders.Names.CONTENT_ENCODING, "utf-8"); response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain"); response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes()); ctx.writeAndFlush(response); } } }
From source file:org.apache.hyracks.http.server.AbstractServlet.java
License:Apache License
@Override public void handle(IServletRequest request, IServletResponse response) { try {//from w w w . j a v a 2s. c o m final HttpMethod method = request.getHttpRequest().method(); if (HttpMethod.GET.equals(method)) { get(request, response); } else if (HttpMethod.HEAD.equals(method)) { head(request, response); } else if (HttpMethod.POST.equals(method)) { post(request, response); } else if (HttpMethod.PUT.equals(method)) { put(request, response); } else if (HttpMethod.DELETE.equals(method)) { delete(request, response); } else if (HttpMethod.OPTIONS.equals(method)) { options(request, response); } else { notAllowed(method, response); } } catch (Exception e) { LOGGER.log(Level.WARNING, "Unhandled exception", e); response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR); } catch (Throwable th) { //NOSONAR Just logging and then throwing again try { LOGGER.log(Level.WARNING, "Unhandled throwable", th); } catch (Throwable loggingFailure) {// NOSONAR... swallow logging failure } throw th; } }
From source file:org.apache.hyracks.http.server.AbstractServlet.java
License:Apache License
@SuppressWarnings("squid:S1172") protected void post(IServletRequest request, IServletResponse response) throws Exception { // designed to be extended but an error in standard case notAllowed(HttpMethod.POST, response); }
From source file:org.asynchttpclient.Dsl.java
License:Open Source License
public static RequestBuilder post(String url) { return request(HttpMethod.POST.name(), url); }