首页 > 解决方案 > 如何正确读取输入流?

问题描述

我有从 SOAPUI 应用程序调用的端点并且一切正常,我的意思是我正在接收我期望的 XML 响应。但是当我通过我的java应用程序来响应时,我得到了奇怪的字符,比如

テ 0  D  E r ￱ ᅯ l ᅴ S

这是我正在使用的代码:

Url url = new URL(endpoint);
connection = (HttpURLConnection) url.openConnection();
            connection.setUseCaches(false);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Accept-Encoding", "gzip, deflate");
            connection.setRequestProperty("Accept", "*/*");
            connection.setRequestProperty("Cache-Control", "no-cache");
            connection.setRequestProperty("Authorization",
                    "Basic " + Base64.encode("username:password".getBytes()));
            connection.setRequestProperty("Content-Type", "text/xml");

BufferedInputStream response = new BufferedInputStream(connection.getInputStream());

byte[] bb = new byte[Integer.parseInt(connection.getHeaderFields().get("Content-Length").get(0))];

for (int i = 0; i < bb.length; i++) {
  bb[i] = (byte) response.read();
  System.out.printf("%s ", (char) bb[i]);
}

我在这里发现了许多帖子,它们提供了许多如何读取流的方法,我正在尝试:BufferedInputStream、InputStream、DataInputStream、DataByteArrayStream 等等,但结果总是相同的。服务器是否有可能向我发送一些错误的编码信息和数据?因为我可以在 SOAPUI 和 POSTMAN 应用程序中看到响应来自 UTF8,但我无法从我的应用程序中正确读取它们。

标签: javahttpurlconnection

解决方案


推荐阅读