How to read input stream properly?

时间:2019-05-31 11:50:07

标签: java httpurlconnection

I have endpoint which I am calling from SOAPUI application and everything is working, I mean I am receiving XML response which I expecting. But when I am doing it by my java app in response I am getting strange chars like

テ 0  D  E r ￱ ᅯ l ᅴ S

Here is my code which I am using:

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]);
}

I found many post here which provide many ways how to read stream and I was trying: BufferedInputStream, InputStream, DataInputStream, DataByteArrayStream and much more but result always is the same. Is it possible that server sending me some wrong encoding information and data? Cause I can see in SOAPUI and POSTMAN apps that response is coming in UTF8 but I am unable to read them properly from my app.

0 个答案:

没有答案