当前位置: 代码迷 >> Android >> Android HTTPUrlConnection响应返回垃圾
  详细解决方案

Android HTTPUrlConnection响应返回垃圾

热度:54   发布时间:2023-08-04 11:30:57.0

这是我输入流标题的代码

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 Content-Type: application/json; charset=UTF-8所以我尝试添加

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

但没有帮助。

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

有人能提供一些帮助吗?

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

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

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

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

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