2011-03-09 49 views
8

因此,我使用Apache Commons HTTP向网页发出请求。我不能为了我的生活找出如何从页面获取实际内容,我只能得到它的标题信息。我如何从中获得实际内容?从Apache Commons HTTP请求获取页面内容

这里是我的示例代码:

HttpGet request = new HttpGet("http://URL_HERE/"); 

HttpClient httpClient = new DefaultHttpClient(); 
HttpResponse response = httpClient.execute(request); 

System.out.println("Response: " + response.toString()); 

谢谢!

回答

1

如果你只是想在URL的内容,你可以使用URL API,像这样:

import java.io.IOException; 
import java.net.URL; 
import java.util.Scanner; 

public class URLTest { 
    public static void main(String[] args) throws IOException { 
     URL url = new URL("http://www.google.com.br"); 
     //here you have the input stream, so you can do whatever you want with it! 
     Scanner in = new Scanner(url.openStream()); 
     in.nextLine(); 
    } 
} 
+0

我刚刚用这个,但我需要使用Apache的百科全书,因为这是一起有更多的东西。 – Chiggins 2011-03-09 01:39:33

14

BalusC的评论将工作得很好。 如果您使用4或Apache HttpComponents的新版本,有一个方便的方法,你可以使用,以及: EntityUtils.toString(HttpEntity);

下面是它会看起来像在你的代码:

HttpGet request = new HttpGet("http://URL_HERE/"); 
HttpClient httpClient = new DefaultHttpClient(); 
HttpResponse response = httpClient.execute(request); 
HttpEntity entity = response.getEntity(); 
String entityContents = EntityUtils.toString(entity); 

我希望这对你有帮助。

不知道这是由于不同的版本,但我不得不把它改写这样的:

HttpGet request = new HttpGet("http://URL_HERE/"); 
CloseableHttpClient httpClient = HttpClients.createDefault(); 
HttpResponse response = httpClient.execute(request); 
HttpEntity entity = response.getEntity(); 
String entityContents = EntityUtils.toString(entity); 
+1

对我有帮助,谢谢! – 2012-12-02 19:54:16

+0

我很高兴听到这个消息。 :) – SecondSun24 2013-01-07 22:18:21