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

时间:2016-08-03 19:28:05

标签: android httpurlconnection

如何使用HttpURLConnection从Android API 18及以上版本获取网站内容?该代码适用于API 23,但是输入流返回API 18的奇数值。这是我尝试使用API​​ 18从URL读取数据时得到的结果:

  

TTP / 1.1 200 OK内容类型:application / json;字符集= utf-8的   Access-Control-Allow-Origin:* Cache-Control:无缓存,无存储,   max-age = 0,must-revalidate Pragma:no-cache Expires:Mon,1990年1月1日   00:00:00 GMT日期:2016年8月3日星期三19:01:33 GMTContent-Encoding: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了解更多信息   info。“X-Content-Type-Options:nosniff X-Frame-Options:SAMEORIGIN   X-XSS-Protection:1; mode = block服务器:GSE Set-Cookie:   NID = 83 = Nb29w9eQo3Fdx_bQuj6YbdLwSfxjuQT4f1Lcb87IbTXQqdGGh6OyuxxB0XGWxNIiAfMdCePDtDb5P9vMYQvbln7svacSJjFkWnU6-B4AN9vLHHY4RUdL3Xny7zSmE8Lm;域= .googleusercontent.com;路径= /;过期=星期四,   02-Feb-2017 19:01:33 GMT; HttpOnly Set-Cookie:   NID = 83 = Z9EmVPVCfKYu4FrAHTVHDPMNM80s23cO6P1VqJAocZHnrQb8QFPKW9BLjQGu5xKOwtqNaT38gTZVJm1zmbT7tVhZAYCQlaSb7dRiSTcqQ71a41cIs4l67RxEkOjXfttC;域= .googleusercontent.com;路径= /;过期=星期四,   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

这背后的原因是什么?如果需要,我可以提供代码。我对此很新,无法在任何地方找到答案。

要从网址获取回复,请使用

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

2 个答案:

答案 0 :(得分:1)

我遇到了类似的问题。问题是您在https请求中使用HttpUrlConnection。因此,您的所有数据都将被加密。我建议使用kevinsawicki:https://github.com/kevinsawicki/http-request之类的其他HttpRequest库,如 http-request 。这将很容易获得有关请求的标题,正文(Json,XML,Plaintext)和其他元数据。

如何添加maven 在android studio中打开项目查看器并打开build.gradle(app) 并在依赖项列表中添加此行

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

最好的问候,大卫

答案 1 :(得分:0)

你可能需要

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