简体   繁体   中英

Sending POST request with body in netty

I want to do POST request to some API by netty. Request must contains parameters as form-data in body. How I try to do this:

   FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, POST, url);
   httpRequest.setUri("https://url.com/myurl");
   ByteBuf byteBuf = Unpooled.copiedBuffer(myParameters, Charset.defaultCharset());
   httpRequest.headers().set(ACCEPT_ENCODING, GZIP);
   httpRequest.headers().set(CONTENT_TYPE, "application/json");
   httpRequest.headers().set(CONTENT_LENGTH, byteBuf.readableBytes());
   httpRequest.content().clear().writeBytes(byteBuf);
   Bootstrap b = new Bootstrap();
   b.group(group)
            .channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CNXN_TIMEOUT_MS)
            .handler(new ChannelInitializerCustomImpl());

   ChannelFuture cf = b.connect(url.getHost(), port);
   cf.addListener(new ChannelFutureListenerCustomImpl();

That's worked ok, but result is different from I received by postman or other instruments. What's the correct way to set my parameters as form-data to request body?

I solved this problem by using Apache httpcomponents library to create HtppEntity , serialize it to byte array and set to netty ByteBuf and also use jackson for parse json from String to Map:

    Map<String, String> jsonMapParams = objectMapper.readValue(jsonStringParams, new TypeReference<Map<String, String>>() {});

    List<NameValuePair> formParams = jsonMapParams.entrySet().stream()
            .map(e -> new BasicNameValuePair(e.getKey(), e.getValue()))
            .collect(Collectors.toList());
    HttpEntity httpEntity = new UrlEncodedFormEntity(formParams);
    ByteBuf byteBuf = Unpooled.copiedBuffer(EntityUtils.toByteArray(httpEntity));

    httpRequest.headers().set(ACCEPT_ENCODING, GZIP);
    httpRequest.headers().set(CONTENT_TYPE, "application/x-www-form-urlencoded");
    httpRequest.headers().set(CONTENT_LENGTH, byteBuf.readableBytes());
    httpRequest.content().clear().writeBytes(byteBuf);

我认为您的请求标头设置不正确,要将content_type设置为“ application / x-www-form-urlencoded”并尝试一下。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM