Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android HTTPUrlConnection response returns garbage

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)
    builder.append(inputLine);

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?

like image 957
Naveen Dissanayake Avatar asked Oct 25 '15 09:10

Naveen Dissanayake


1 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    
like image 177
Hash Avatar answered Nov 20 '22 18:11

Hash