1

I have an HttpUrlConnection and I can get response Headers from it like below:

How to read full response from HttpURLConnection?

But I've tried many ways to get the response Body without success. For example:

br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
sb = new StringBuilder();
String output;
while ((output = br.readLine()) != null) {
sb.append(output);
return sb.toString();

Or

Other ways... (With UTF-8 Encoding and ...)

The problem is that the result contains invalid character. For instance if the response is an image, I cannot have the correct image and it contains invalid characters:

The Correct Image:

‰PNG


IHDR  è  £   ؟£?b       pHYs     ڑœ  
OiCCPPhotoshop ICC profile  xع‌SgTSé=÷قôBKˆ€”KoR RB‹€‘&*!   Jˆ!،ظQءEEب ˆژژ€ŒQ,ٹ

The Incorrect Image: (What I've got from response body)

<>�t:�t�R���k�ҥ��c�ƍZ�n�6mڤW^y���
6���/׼y�1���B��������ƍ;
�˖-�'�|�+V��h�Z�e�3����%%%)--M�����/��   � �}h��m6�JKK��Oh�����㏽�QWW���T%&&*++��s���ph���III�<�%%%)<<�#�),,L+V����ý����TII����x�b=��*--�Z���M�2�l�nt�ө��|�{�z��ǵe���<??_�g�VVV���={��?^�|��wF����<͟?_���gmP:  �:� �C�|���t�R���r:�z������{}���B���k���o�$
>\���^�?!!Ak׮լY�$�j�%Wq�ݮu��i���r:�

How can I get the response body from HttpUrlConnection WITHOUT any changes with correct characters (formatting, encoding and ...)?

Vahid
  • 3,384
  • 2
  • 35
  • 69

1 Answers1

2

If the body is a PNG image, it will be binary data, and you're expected to use the inputstream, not a reader.

UPDATE:

Example: to store the image in file "myimage.png":

try (InputStream in = conn.getInputStream();
        OutputStream out = new FileOutputStream("myimage.png")) {
    byte[] buf = new byte[4096];
    int n;
    while ((n = in.read(buf)) > 0) {
        out.write(buf, 0, n);
    }
}
Maurice Perry
  • 9,261
  • 2
  • 12
  • 24