gpt4 book ai didi

java - StringEntity 未在打印或套接字写入时对内容进行字符串化

转载 作者:行者123 更新时间:2023-11-29 05:05:46 25 4
gpt4 key购买 nike

我有一些 json 试图作为 BasicHttpResponse 的一部分返回。下面是一个代码片段,我已经对生成的打印输出进行了注释。

我可以在 A 中打印出 json,它在 1 中看起来不错。但是当我在 B 中打印实体时,我在 2 中没有得到任何主体,尽管它确实有长度。如果我进入调试器,我会在那里看到数据。

如果我更改内容类型并打印实体,我可以看到此更改反射(reflect)在 3 中,但同样没有实际的字符串数据。

我正在尝试通过管道推送此数据,而不是在写入时获取 json 正文有点问题。

我的期望是,当我将数据添加到实体然后使用 HttpMessageWriter 打印或写入实体时,将显示/传输 json。我错过了什么?期望 json 打印在 toString 上是不合理的吗?

     BasicHttpResponse resp;
StringEntity entity = new StringEntity(json.toString(), "UTF-8");
A) logger.info("to str: " + json.toString());
B) logger.info("Entity: " + entity);
entity.setContentType("application/json; charset=UTF-8");
resp.setEntity(entity);
C) logger.info("set entity " + resp.getEntity());



1) to str: [{"id":"12","revision":"12","group":"12",
"remote":"12"}]
2) Entity: [Content-Type: text/plain;
charset=UTF-8,Content-Length: 81,Chunked: false]
3) set entity [Content-Type: application/json;
charset=UTF-8,Content-Length: 81,Chunked: false]

最佳答案

StringEntity 的 toString() 方法只会打印您获取的数据,这是正确的行为。

赋给StringEntity的String在对象中保存为字节数组。

这是 StringEntity 的构造函数:

/**
* Creates a StringEntity with the specified content and content type.
*
* @param string content to be used. Not {@code null}.
* @param contentType content type to be used. May be {@code null}, in which case the default
* MIME type {@link ContentType#TEXT_PLAIN} is assumed.
*
* @throws IllegalArgumentException if the string parameter is null
* @throws UnsupportedCharsetException Thrown when the named charset is not available in
* this instance of the Java virtual machine
* @since 4.2
*/
public StringEntity(final String string, final ContentType contentType) throws UnsupportedCharsetException {
super();
Args.notNull(string, "Source string");
Charset charset = contentType != null ? contentType.getCharset() : null;
if (charset == null) {
charset = HTTP.DEF_CONTENT_CHARSET;
}
this.content = string.getBytes(charset);
if (contentType != null) {
setContentType(contentType.toString());
}
}

如果你想再次将你的实体打印为 json(例如用于日志记录,因为它已经在响应中设置)你必须执行如下操作:

logger.info("Entity: " + IOUtils.toString(entity.getContent()));

使用 IOUtils.toString 因为 entity.getContent() 带来了一个 InputStream 对象,你可以随意使用它。

关于java - StringEntity 未在打印或套接字写入时对内容进行字符串化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30398736/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com