在httpclient中,将HttpEntity转换为String的最优雅/正确的方法是什么? [英] In httpclient what is the most elegant/correct way to turn HttpEntity to a String?

查看:5737
本文介绍了在httpclient中,将HttpEntity转换为String的最优雅/正确的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Apache httpcomponents Java库获取网页。在连接结果后,我得到一个 HttpEntity 有一个方法 getContent() 返回 InputStream 并且还有一个方法 writeTo()写入一个OutputStream。

I'm fetching a web page using the Apache httpcomponents Java library. 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.

我想要将结果转换为String以提取信息。什么是最优雅(和安全)的方式?

I want to turn the result into a String for extracting information. What is the most elegant (and safe) way to do this?

一些可能的解决方案:


  • 写入 ByteArrayOutputStream 然后将这些字节转换为带有String构造函数的String

  • 使用InputStreamReader直接读取从流中,并放入一个StringBuilder

  • Write to a ByteArrayOutputStream and then convert those bytes to a String with a String constructor
  • use InputStreamReader to read straight from the stream, and put into a StringBuilder

这些都感觉有点难看。你会建议选择其中一种吗?

Both of these feel a bit ugly. Would you recommend choosing one of these or something else?

推荐答案

那么(伪):

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.

这篇关于在httpclient中,将HttpEntity转换为String的最优雅/正确的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆