【发布时间】:2016-12-09 16:15:59
【问题描述】:
如何使用 HttpURLConnection 为 android API 18 及更高版本从网站获取内容?该代码在 API 23 上运行良好,但 inputstream 为 API 18 返回奇数值。这是我尝试使用 API 18 从 URL 读取数据时得到的结果:
TTP/1.1 200 OK Content-Type: application/json;字符集=utf-8 Access-Control-Allow-Origin: * Cache-Control: no-cache, no-store, max-age=0, must-revalidate Pragma: no-cache Expires: Mon, 01 Jan 1990 格林威治标准时间 00:00:00 日期:2016 年 8 月 3 日,星期三 19:01:33 GMT 内容编码:gzip P3P: CP="这不是 P3P 策略!请参阅 https://support.google.com/accounts/answer/151657?hl=en 了解更多 info." P3P: CP="这不是 P3P 策略!看 https://support.google.com/accounts/answer/151657?hl=en 了解更多 信息。” X-Content-Type-Options: nosniff X-Frame-Options: SAMEORIGIN X-XSS-防护:1;模式=阻止服务器:GSE 设置 Cookie: NID=83=Nb29w9eQo3Fdx_bQuj6YbdLwSfxjuQT4f1Lcb87IbTXQqdGGh6OyuxxB0XGWxNIiAfMdCePDtDb5P9vMYQvbln7svacSJjFkWnU6-B4AN9vLHHY4RUdL3Xny7zSmE8Lm;域=.googleThucontent.com; 格林威治标准时间 2017 年 2 月 2 日 19:01:33;HttpOnly 设置 Cookie: NID=83=Z9EmVPVCfKYu4FrAHTVHDPMNM80s23cO6P1VqJAocZHnrQb8QFPKW9BLjQGu5xKOwtqNaT38gTZVJm1zmbT7tVhZAYCQlaSb7dRiSTcqQ71a41cIs4l67RxEkOjXfttC;域=.googleThuusercontent.com;路径=/;过期 格林威治标准时间 2017 年 2 月 2 日 19:01:33;HttpOnly 替代协议:443:quic Alt-Svc: quic=":443";马=2592000; v="36,35,34,33,32,31,30" 传输编码:分块 00000001 00000001 � 00000001 00000001 �� 00000001 �� 00000001 �� 00000001 �� �� ��
这背后的原因是什么?如果需要,我可以提供代码。我对此很陌生,无法在任何地方找到答案。
从我使用的 URL 获取响应
private String downloadUrl(String urlString) throws IOException {
InputStream is = null;
try {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int responseCode = conn.getResponseCode();
is = conn.getInputStream();
String contentAsString = convertStreamToString(is);
return contentAsString;
} finally {
if (is != null) {
is.close();
}
}
}
以及将流转成字符串的方法
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
【问题讨论】:
-
请求的 url 是 ...?
-
@Olayinka 请求地址是script.googleusercontent.com/macros/…
-
我稍后将其转换为 JSONObject,这一切都适用于 API 23。
-
我们能不能也看看你调用url并提取数据的代码
-
@Olayinka github.com/AndreasLoL/NutikorvAlphaRelease/blob/master/app/src/… 这是我用来提取数据的类。