java - Http(s) 请求以垃圾字符响应
问题描述
我正在尝试向网站发送请求以从中获取一些数据。但是,响应是垃圾字符,例如:
Ì 3ú¢¸<N¤@H±ü>§#Fe®¡+K·fÐcıaOqâò;'Êù!°â<rº\¼YDóß1K`òúüb¨ÑTcíÆ
这只发生在包含数据的 repose 中,并且错误也可以正常工作。响应应该如下所示(来自浏览器请求):
{"d":[{"__type":"CalendarTransport:http:...","activityId":2662,"activityImportIdentifier":null,"activityType":1,"allDay":false,"attendanceMode":1,....
这是我的代码
try
{
HttpsURLConnection httpsURLConnection;
httpsURLConnection = (HttpsURLConnection) new URL("https", redacted, redacted).openConnection();
try
{
httpsURLConnection.setRequestMethod("POST");
}
catch (Exception e)
{
Log.d(TAG, "doInBackground: oh no (3) it's a " + e.toString());
}
httpsURLConnection.setRequestProperty("Accept-Charset", "*/*");
httpsURLConnection.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
httpsURLConnection.setRequestProperty("Connection", "keep-alive");
httpsURLConnection.setRequestProperty("Content-Type", "application/json");
httpsURLConnection.setRequestProperty("Cookie", new DomainCookies(redacted).toRequestHeader());
httpsURLConnection.setDoOutput(true);
httpsURLConnection.setDoInput(true);
OutputStream os = httpsURLConnection.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
osw.write(redacted);
osw.flush();
osw.close();
os.close();
StringBuilder mssg = new StringBuilder();
DataInputStream inputStream;
int status = httpsURLConnection.getResponseCode();
if (status != HttpsURLConnection.HTTP_OK)
{
inputStream = new DataInputStream(httpsURLConnection.getErrorStream());
Log.d(TAG, "doInBackground: HTTP error");
}
else
{
inputStream = new DataInputStream(httpsURLConnection.getInputStream());
Log.d(TAG, "doInBackground: HTTP OK");
}
try
{
for(int c = inputStream.read(); inputStream.available() != 0; c = inputStream.read())
{
mssg.append((char)c);
}
Log.d(TAG, "doInBackground: " + mssg);
}
catch (Exception e)
{
Log.d(TAG, "doInBackground: oh no (1) it's a " + e.toString());
}
}
catch (MalformedURLException e)
{
Log.d(TAG, "onCreate: Oh no it's a " + e.toString());
}
catch (Exception e)
{
Log.d(TAG, "doInBackground: Oh no it's a " + e.toString());
}
浏览器可以得到很好的响应,一定是我正在做的事情(或android,但我怀疑)
解决方案
我将从摆脱这条线开始:
httpsURLConnection.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
您的代码没有处理这些形式的数据编码,因此不要要求服务器以这种方式对数据进行编码。
除此之外......现在是 2018 年。停止使用HttpsURLConnection
. 使用更现代且不易出错的东西,例如OkHttp。
推荐阅读
- react-native - React Native 的 NetInfo 在 iOS 和 Android 上的不同行为
- mysql - 为什么这个结果会发生两次?相隔几分钟
- python - 根据坐标重采样和插值栅格
- java - Keycloak 桌面 java 适配器删除 KEYCLOAK_IDENTITY cookie
- android - Android Flow 支持的 Firestore 实时侦听器在配置更改时被取消
- javascript - 如何在 Gatsby 项目中加载索引文件
- arrays - 给定数组的所有子数组的 MEX 总和
- telegram-bot - Telegram api 让用户最后一次看到
- laravel - Laravel 规则忽略和删除_at null
- javascript - 疯狂的同时 javascript 数组 concat 会干扰自己