Cannot POST JSON on server using Netty

I am stuck in a really, really basic problem: using the HttpRequest to POST JSON bit for the server using Netty.

As soon as the channel is connected, I prepare the request as follows:

 HttpRequest request = new DefaultHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.POST, postPath); request.setHeader(HttpHeaders.Names.CONTENT_TYPE, "application/json"); String json = "{\"foo\":\"bar\"}"; ChannelBuffer buffer = ChannelBuffers.copiedBuffer(json, CharsetUtil.UTF_8); request.setContent(buffer); channel.write(request); System.out.println("sending on channel: " + json); 

The last line prints {"foo":"bar"} , which is valid JSON.

However, in fact, a simple echo server that I wrote in Python using Flask shows a request, but it does not have a body or json field, for example, the body cannot be parsed correctly in JSON.

When I just use curl to send the same data, then the echo server correctly finds and parses JSON:

 curl --header "Content-Type: application/json" -d '{"foo":"bar"}' -X POST http://localhost:5000/post_path 

My pipeline in Netty is formed using:

 return Channels.pipeline( new HttpClientCodec(), new MyUpstreamHandler(...)); 

Where MyUpstreamHandler extends SimpleChannelUpstreamHandler and tries to send an HttpRequest after connecting the channel.

Again, I have a complete loss. Any help would be greatly appreciated.

+4
source share
2 answers

Not sure if you have http keep alive on or not, but if you do, you may have to send the length of the content in the header.

+3
source

As Veebs said, you need to set some HTTP headers, I also had the same problem and I lost hours, I got it working with the following code :).

  import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.*; ...... HttpRequest httpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/post_path"); final ChannelBuffer content = ChannelBuffers.copiedBuffer(jsonMessage, CharsetUtil.UTF_8); httpRequest.setHeader(CONTENT_TYPE, "application/json"); httpRequest.setHeader(ACCEPT, "application/json"); httpRequest.setHeader(USER_AGENT, "Netty 3.2.3.Final"); httpRequest.setHeader(HOST, "localhost:5000"); httpRequest.setHeader(CONNECTION, "keep-alive"); httpRequest.setHeader(CONTENT_LENGTH, String.valueOf(content.readableBytes())); httpRequest.setContent(content); channel.write(httpRequest); 
+8
source

Source: https://habr.com/ru/post/1403760/


All Articles