当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Different content with Apache's DefaultHttpClient and HttpURLConnection

问题描述:

I want to read the content of a website (http://www.google.com) in an Android app. Using the deprecated DefaultHttpClient still works fine and I always get a content length of about 15.000 characters:

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

However, when I use a HttpURLConnection to achieve the same, I get a different content with a length of about 100.000 characters.

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

Does anybody know, why there is such a big difference. Thanks!

网友答案:

The problem is caused by the user agent. With the following code, the two requests behave the same:

connection.setRequestProperty("User-Agent","Apache-HttpClient");
分享给朋友:
您可能感兴趣的文章:
随机阅读: