【问题标题】:Sending POST request with body in netty在 netty 中发送带有正文的 POST 请求
【发布时间】:2017-08-08 18:59:03
【问题描述】:

我想通过 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 以请求正文的正确方法是什么?

【问题讨论】:

    标签: java http netty


    【解决方案1】:

    我通过使用 Apache httpcomponents 库来创建 HtppEntity,将其序列化为字节数组并设置为 netty ByteBuf 并使用 jackson 将 json 从 String 解析为 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);
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2016-01-25
        • 1970-01-01
        • 2021-01-03
        • 2013-11-13
        • 2021-03-12
        • 2019-03-15
        • 2016-02-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多