In httpclient what is the most elegant/correct way to turn HttpEntity to a String?

南笙酒味 提交于 2019-12-07 04:58:47

问题


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.

I want to turn the result into a String for extracting information. 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
  • 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?


回答1:


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.




回答2:


System.out.println( EntityUtils.toString(httpResponse.getEntity()) );




回答3:


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.



来源:https://stackoverflow.com/questions/2043580/in-httpclient-what-is-the-most-elegant-correct-way-to-turn-httpentity-to-a-strin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!