Home » Android » java – Android HTTPUrlConnection response returns garbage

java – Android HTTPUrlConnection response returns garbage

Posted by: admin May 14, 2020 Leave a comment


Here is my code for header the inputstream

mResponseCode = connection.getResponseCode();

mError = mResponseCode != 200 && mResponseCode != 201 && mResponseCode != 202;

if (mError) {
    inputStream = connection.getErrorStream();
} else {
    inputStream = connection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
bufferedReader = new BufferedReader(inputStreamReader);

String inputLine;
final StringBuilder builder = new StringBuilder();

while ((inputLine = bufferedReader.readLine()) != null)

resultStr = builder.toString();

but the string returns garbage values like this “���������������}”

The response header includes Content-Type: application/json; charset=UTF-8 so I tried adding

inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));

but didn’t help.

its working perfectly on postman so I know it not something wrong with the service.

Can someone offer some assistance?

How to&Answers:

Some service try to compress data they produce with the help of header parameters like:

Content-Encoding: SomeKindOfEncoding

To disable this feature try to set the accept encoding:

connection.setRequestProperty("Accept-Encoding", "identity");

If you would like to save some transfer data on the mobile phone use the following:

connection.setRequestProperty("Accept-Encoding", "gzip"); //optional forcing gzip
inputStream = new GZIPInputStream(connection.getInputStream());
//rest of the code