在netty中发送带有body的POST请求

时间:2017-08-01 10:24:45

标签: java http 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以请求正文的正确方法是什么?

2 个答案:

答案 0 :(得分:1)

我通过使用Apache httpcomponents库创建HtppEntity,将其序列化为字节数组并设置为netty ByteBuf并使用jackson来解析此问题来解决此问题要映射的字符串:

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

答案 1 :(得分:0)

我认为您的请求标头设置不正确,将content_type设置为&#34; application / x-www-form-urlencoded&#34;并试一试。