Java 发送邮件请求,邮件正文在netty中
我想通过netty对一些API进行POST请求。请求必须在正文中包含作为表单数据的参数。我是如何做到这一点的:Java 发送邮件请求,邮件正文在netty中,java,http,netty,Java,Http,Netty,我想通过netty对一些API进行POST请求。请求必须在正文中包含作为表单数据的参数。我是如何做到这一点的: FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, POST, url); httpRequest.setUri("https://url.com/myurl"); ByteBuf byteBuf = Unpooled.copiedBuffer(myParamet
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();
这是工作正常,但结果是不同的,我收到的邮递员或其他文书。
将我的参数设置为请求正文的表单数据的正确方法是什么?我认为您的请求标题设置不正确,请将内容类型设置为application/x-www-form-urlencoded并尝试一下。我通过使用Apache httpcomponents库创建HttpEntity解决了这个问题,将其序列化为字节数组并设置为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);