[英]In httpclient what is the most elegant/correct way to turn HttpEntity to a String?
I'm fetching a web page using the Apache httpcomponents Java library . 我正在使用Apache httpcomponents Java库获取一个网页。 After connecting the result I get is an
HttpEntity
which has a method getContent()
which returns an InputStream
and also has a method writeTo()
which writes to an OutputStream. 在连接结果之后,我得到一个
HttpEntity
,它有一个方法getContent()
,它返回一个InputStream
,还有一个写入OutputStream的方法writeTo()
。
I want to turn the result into a String for extracting information. 我想将结果转换为String以提取信息。 What is the most elegant (and safe) way to do this?
最优雅(和安全)的方法是什么?
Some possible solutions: 一些可能的解决方
ByteArrayOutputStream
and then convert those bytes to a String with a String constructor ByteArrayOutputStream
,然后使用String构造函数将这些字节转换为String Both of these feel a bit ugly. 这些都感觉有点难看。 Would you recommend choosing one of these or something else?
你会建议选择其中之一吗?
System.out.println(EntityUtils.toString(httpResponse.getEntity()));
What about (pseudo): 怎么样(伪):
BasicResponseHandler handler = new org.apache.http.impl.client.BasicResponseHandler ();
String str = httpClient.execute(request, handler);
You would have to handle exceptions on your own in this case. 在这种情况下,您必须自己处理异常。
It may be ugly, but I think that's the only way to do it. 它可能很难看,但我认为这是唯一的方法。 You can use IOUtils.toString() from Commons-IO though without having to write your own code.
您可以使用Commons-IO中的IOUtils.toString() ,而无需编写自己的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.