[英]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
以请求正文的正确方法是什么?
我通过使用Apache httpcomponents
库创建HtppEntity
,将其序列化为字节数组并设置为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);
我认为您的请求标头设置不正确,要将content_type设置为“ application / x-www-form-urlencoded”并尝试一下。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.