使用 HttpURLConnection 从网站获取内容 (Android API 18)

Getting content from website with HttpURLConnection (Android API 18)

对于 android API 18 岁及以上的人,如何使用 HttpURL 连接从网站获取内容?该代码对于 API 23 工作正常,但输入流返回 API 18 的奇数值。这是我尝试使用 API 从 URL 读取数据时得到的结果18:

TTP/1.1 200 OK Content-Type: application/json; charset=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 GMT Date: Wed, 03 Aug 2016 19:01:33 GMTContent-Encoding: gzip P3P: CP="This is not a P3P policy! See https://support.google.com/accounts/answer/151657?hl=en for more info." P3P: CP="This is not a P3P policy! See https://support.google.com/accounts/answer/151657?hl=en for more info." X-Content-Type-Options: nosniff X-Frame-Options: SAMEORIGIN X-XSS-Protection: 1; mode=block Server: GSE Set-Cookie: NID=83=Nb29w9eQo3Fdx_bQuj6YbdLwSfxjuQT4f1Lcb87IbTXQqdGGh6OyuxxB0XGWxNIiAfMdCePDtDb5P9vMYQvbln7svacSJjFkWnU6-B4AN9vLHHY4RUdL3Xny7zSmE8Lm;Domain=.googleusercontent.com;Path=/;Expires=Thu, 02-Feb-2017 19:01:33 GMT;HttpOnly Set-Cookie: NID=83=Z9EmVPVCfKYu4FrAHTVHDPMNM80s23cO6P1VqJAocZHnrQb8QFPKW9BLjQGu5xKOwtqNaT38gTZVJm1zmbT7tVhZAYCQlaSb7dRiSTcqQ71a41cIs4l67RxEkOjXfttC;Domain=.googleusercontent.com;Path=/;Expires=Thu, 02-Feb-2017 19:01:33 GMT;HttpOnly Alternate-Protocol: 443:quic Alt-Svc: quic=":443"; ma=2592000; v="36,35,34,33,32,31,30" Transfer-Encoding: chunked 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();
    }

我遇到过类似的问题。问题是您在 https 请求上使用了 HttpUrlConnection。因此,您的所有数据都将被加密。我建议使用其他一些 HttpRequest 库,例如 kevinsawicki 的 http-requesthttps://github.com/kevinsawicki/http-request。这将轻松支持获取 headers、正文(Json、XML、纯文本)和有关请求的其他元数据。

如何添加maven 在 android 工作室中打开项目查看器并打开 build.gradle(应用程序) 并将这一行添加到依赖项列表

compile 'com.github.kevinsawicki:http-request:6.0'

现在打开(项目)build.gradle 并确保在存储库下有这个

mavenCentral()

示例获取请求

HttpRequest req = HttpRequest.get("https://google.com");
req.trustAllCerts();
req.trustAllHosts(); //If you are having certificate problems
int code = req.code();
String body = req.body();
Log.d("CODE:", String.valueOf(code));
Log.d("BODY:", body);

最好的问候,大卫

您可能需要

 in = new InputStreamReader(
                    httpResponseCode == HttpURLConnection.HTTP_OK ? conn.getInputStream() : conn.getErrorStream(),
                    "UTF-8");