在 netty 中发送 POST 请求正文

Sending POST request with body in netty

我想通过 netty 向某些 API 请求 POST。请求必须在正文中包含 form-data 参数。我如何尝试这样做:

   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();

一切正常,但结果与我通过 postman 或其他仪器收到的结果不同。 将我的参数设置为 form-data 以请求正文的正确方法是什么?

我认为你的要求 header 设置不正确,将 content_type 设置为 "application/x-www-form-urlencoded" 试试看。

我通过使用 Apache httpcomponents 库创建 HtppEntity 解决了这个问题,将其序列化为字节数组并设置为 netty ByteBuf 并使用 jackson 进行解析json 从字符串到映射:

    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);