[英]Preserve a HTTPEntity without consuming the stream
I'm using org.apache.http.client.HttpClient and I'm trying to access the payload of the request HTTPEntity without consuming the underlying stream.我正在使用 org.apache.http.client.HttpClient 并且我试图在不消耗底层 stream 的情况下访问请求 HTTPEntity 的有效负载。 I tried using我尝试使用
EntityUtils.toString(someEntity);
but this consumes the stream.但这会消耗 stream。 I just want to preserve the payload which was sent in a HTTP request to a String object for eg我只想保留在 HTTP 请求中发送到字符串 object 的有效负载,例如
Sample Code:示例代码:
String uri = "someURI";
HttpPut updateRequest = new HttpPut(uri);
updateRequest.setEntity(myHttpEntity);
Any hint appreciated.任何提示表示赞赏。
A HttpEntity must be repeatable
for it to be repeatedly consumable. HttpEntity 必须是repeatable
的,它才能被重复使用。 The method isRepeatable()
shows whether or not this is the case.方法isRepeatable()
显示是否是这种情况。
Two entities are repeatable:两个实体是可重复的:
This means you have to add one of these to the original request so you can keep using using its content.这意味着您必须将其中之一添加到原始请求中,以便您可以继续使用其内容。
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"));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.