java - 在不消耗流的情况下保留 HTTPEntity
问题描述
我正在使用 org.apache.http.client.HttpClient 并且我正在尝试访问请求 HTTPEntity 的有效负载而不消耗底层流。我尝试使用
EntityUtils.toString(someEntity);
但这会消耗流。我只想保留在 HTTP 请求中发送到 String 对象的有效负载,例如
示例代码:
String uri = "someURI";
HttpPut updateRequest = new HttpPut(uri);
updateRequest.setEntity(myHttpEntity);
任何提示表示赞赏。
解决方案
HttpEntity 必须是repeatable
可重复使用的。该方法isRepeatable()
显示是否是这种情况。
两个实体是可重复的:
- 字符串实体
- 字节数组实体
这意味着您必须将其中之一添加到原始请求中,以便您可以继续使用其内容。
public void doExample() {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPut httpPut = new HttpPut("some_url");
httpPut.setHeader(CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
StringEntity jsonEntityOrso = new StringEntity("{ \"hello\": \"some message\" }");
httpPut.setEntity(jsonEntityOrso);
StringEntity reusableEntity = (StringEntity) httpPut.getEntity();
String hello = readInputStream(reusableEntity.getContent());
String hello2 = readInputStream(reusableEntity.getContent());
boolean verify = hello.equals(hello2); // returns true
}
private String readInputStream(InputStream stream) {
return new BufferedReader(
new InputStreamReader(stream, StandardCharsets.UTF_8))
.lines()
.collect(Collectors.joining("\n"));
}
推荐阅读
- swift - UIActivityViewController 从 activityItems 中删除项目
- java - 数组内的变量未在 Java 中更新其值
- python-3.x - 如何使用 Pandas 对 txt 文件中的多个长字符串进行切片?
- regex - 如何在 Flutter 中使用正则表达式获取文本中的字符串
- php - Laravel 为相同的资源路由调用不同的控制器
- c# - 如何在视图中制作项目列表并将其添加到列表中的产品中
- c++ - 在 C++ 中使用 tinyxml 库读取 xml 文件时忽略注释掉的标签
- sql-server - 存储过程更改不反映 dacpac 脚本中的大小写敏感性
- typescript - react-native - fetch:网络请求失败
- wpf - 继承 DatagridColumnHeader 并使用它