response.asXml()始终在Play Framework上返回编码错误

时间:2016-01-06 07:10:19

标签: java playframework playframework-2.4

我正在玩framweork应用程序。 我试图从Web服务获取xml内容。 http://example.com/api返回xml,但其编码为EUC-JP。 (字符集= EUC-JP)

我写了以下代码。

WSRequest request = ws.url("http://example.com/api");
WSRequest complexRequest = request.setHeader("Accept", "application/xml")
    .setContentType("application/x-www-form-urlencoded");
Promise<Document> documentPromise = complexRequest.post("key1=value1").map(response -> {
    String name = XPath.selectText("//name", response.asXml());
    System.out.println("name :" + name);
    return response.asXml();
});

但是,response.asXml()始终返回错误:

[Fatal Error] :xx:xx: Invalid byte 1 of 1-byte UTF-8 sequence.

如何使用response.asXml获取数据而没有任何错误?

1 个答案:

答案 0 :(得分:0)

最后,我代表asXml使用了DocumentBuilder,就像 How to fix Invalid byte 1 of 1-byte UTF-8 sequence

  Promise<Result> resultPromise = request.post("key=" + value).map(response -> {
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    ByteArrayInputStream stream = new ByteArrayInputStream(response.getBody().getBytes("euc-jp"));
    String name = XPath.selectText("//name", builder.parse(stream)));
    System.out.println("name :" + name);

    return ok(main.render());
  });