与Apache的DefaultHttpClient和HttpURLConnection不同的内容

时间:2016-12-27 16:13:47

标签: java android http

我想在Android应用中阅读网站内容(http://www.google.com)。使用已弃用的DefaultHttpClient仍然可以正常工作,我总是得到大约15.000个字符的内容长度:

DefaultHttpClient client = new DefaultHttpClient();
HttpGet g = new HttpGet(target);
HttpResponse res = client.execute(g);
InputStream is = res.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuilder builder = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        builder.append(line);
    }
return Base64.encodeToString(builder.toString().getBytes(), Base64.NO_WRAP);

但是,当我使用HttpURLConnection实现相同的功能时,我会得到一个长度约为100.000个字符的不同内容。

HttpURLConnection connection = (HttpURLConnection) new URL(target).openConnection();
InputStream is = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuilder builder = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        builder.append(line);
    }
return Base64.encodeToString(builder.toString().getBytes(), Base64.NO_WRAP);

有谁知道,为什么会有这么大的差异。谢谢!

1 个答案:

答案 0 :(得分:0)

问题是由用户代理引起的。使用以下代码,这两个请求的行为相同:

connection.setRequestProperty("User-Agent","Apache-HttpClient");