Android HTTPUrlConnection响应返回垃圾

时间:2015-10-25 09:53:10

标签: java android httpurlconnection

这是我输入流标题的代码

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();

但字符串会返回这样的垃圾值"���������������}"

响应标头包含Content-Type: application/json; charset=UTF-8,因此我尝试添加

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

但没有帮助。

它完全适用于邮递员,所以我知道这项服务并没有出错。

有人可以提供帮助吗?

1 个答案:

答案 0 :(得分:3)

某些服务尝试使用标头参数压缩它们生成的数据,如:

  

Content-EncodingSomeKindOfEncoding

要禁用此功能,请尝试设置接受编码:

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

如果您想在手机上保存一些传输数据,请使用以下命令:

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