java - 如何正确读取输入流?
问题描述
我有从 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,但我无法从我的应用程序中正确读取它们。
解决方案
推荐阅读
- mongodb - Go + MongoDB:多态查询
- php - PHP 使用 Intelephense 调用 mysqli 的正确方法
- javascript - 浏览器中的 OpenSSL - 需要从 .pem 获取私钥然后签名
- javascript - 每次页面访问随机化 stylesheet.css
- react-native - react-native install vs link有什么区别?
- python - TensorFlow 的占位符初始化不同于 TensorFlow 的常量初始化。为什么?
- git - Git windows克隆符号链接
- java - Java左移运算符
- regex - 无法增加在正则表达式匹配的第 1 组中捕获的数字
- javascript - 简单的 D3.js 条形图:组“g”位置和尺寸搞砸了