Java REST Chunked编码

时间:2011-10-13 13:16:06

标签: java rest encoding chunked

我正在尝试使用使用块编码的REST服务读取一些信息。

String encodedURL = URLEncoder.encode(url, "UTF-8");
WebClient client = org.apache.cxf.jaxrs.client.WebClient.create(encodedURL).accept("text/html");
Response response = client.get();

响应包含状态,元数据和实体。元数据包含以下信息:

  

{Date = [星期四,2011年10月13日13:27:02 GMT],Vary = [Accept-Encoding,   User-Agent],Transfer-Encoding = [chunked],Keep-Alive = [timeout = 15,   max = 100],Content-Type = [text / html;字符集的字符集= = UTF-8],   Connection = [Keep-Alive],X-Pad = [避免浏览器错误],   Server = [Apache / 2.2.3(Linux / SUSE)]}

,实体包含sun.net.www.protocol.http.HttpURLConnection $ HttpInputStream类型的实例。

我过去,我一直在使用以下代码行来获取整个结果字符串:

String resultString = client.get(String.class);

但不知何故,这一行引发了一个例外:

  

。阅读响应消息的问题,类:class   java.lang.String,ContentType:text / html; charset = charset = UTF-8。   org.apache.cxf.jaxrs.client.ClientWebApplicationException:.Problem   阅读响应消息,类:class java.lang.String,   ContentType:text / html; charset = charset = UTF-8。

     

...由...引起:

     

引起:java.io.UnsupportedEncodingException:charset = UTF-8 at   sun.nio.cs.StreamDecoder.forInputStreamReader(Unknown Source)at   java.io.InputStreamReader。(未知来源)at   org.apache.cxf.helpers.IOUtils.toString(IOUtils.java:180)at   org.apache.cxf.helpers.IOUtils.toString(IOUtils.java:166)at at   org.apache.cxf.jaxrs.provider.PrimitiveTextProvider.readFrom(PrimitiveTextProvider.java:51)     在   org.apache.cxf.jaxrs.client.AbstractClient.readBody(AbstractClient.java:435)     ......还有49个

是否有直接的解决方案来获取响应的全部内容?

谢谢!

KON

2 个答案:

答案 0 :(得分:2)

您可以使用

@Produces("application/json; charset=UTF-8")

jax-rs服务的注释

答案 1 :(得分:1)

我担心服务器端会发送垃圾并导致异常被抛出到客户端。

有问题的部分是Content-type HTTP标头信息。它被设置为:

text/html; charset=charset=UTF-8

如您所见,重复了 charset 这个词。因此,您的客户端尝试使用名为charset=UTF-8的编码对其进行解码,这当然不存在。

最好的解决方案是在服务器端修复问题。但我不知道你是否能在那里修好它。如果没有,下一个最好的方法是在尝试获取响应内容之前尝试修复HTTP标头。