简体   繁体   English

在httpclient中,将HttpEntity转换为String的最优雅/正确的方法是什么?

[英]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: 一些可能的解决方

  • Write to a ByteArrayOutputStream and then convert those bytes to a String with a String constructor 写入ByteArrayOutputStream ,然后使用String构造函数将这些字节转换为String
  • use InputStreamReader to read straight from the stream, and put into a StringBuilder 使用InputStreamReader直接从流中读取,并放入StringBuilder

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.

相关问题 将Lucene CharArraySet转换为String Set的最优雅方法是什么? - What is the most elegant way to convert a Lucene CharArraySet to a String Set? 检查字符串是否在列表中的最优雅/惯用的方法是什么? - What's the most elegant/idiomatic way to check if a string is in a list? 结合可选项的最优雅方式是什么? - What's the most elegant way to combine optionals? 剥离和替换String模式的最优雅方法 - Most elegant way to strip and replace a String pattern 检测字符串是否为数字的最优雅方法? - Most elegant way to detect if a String is a number? 在Java 8中将映射连接到字符串的最优雅的方法 - Most elegant way to join a Map to a String in Java 8 选择必须使用哪种服务实现的最优雅的方法是什么? - What is the most elegant way to choose what service implementation must be used? Java中执行空检查的最优雅方法是什么 - What is the most elegant way of doing null checks in Java 编程成语言:在Java中定义回调的最优雅方法是什么? - Programming into a language: What is the most elegant way to define callbacks in Java? 检查 boolean 数组中的所有值是否为真的最优雅方法是什么? - What is the most elegant way to check if all values in a boolean array are true?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM