2011-03-09 4 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

난 그냥이 사용했을하지만 난이 더 많은 물건과 함께 있기 때문에 아파치 코 몬즈를 사용하는 데 필요한 . – Chiggins

14

BalusC의 의견은 잘 작동합니다.

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

I : 여기 EntityUtils.toString(HttpEntity);

이 코드에서처럼 보일 수있는 내용 : 당신은 버전 4 또는 Apache HttpComponents의 새로운를 사용하는 경우, 당신은뿐만 아니라 사용할 수있는 편리한 방법이있다 이것이 당신에게 도움이되기를 바랍니다.

이 다른 버전 때문이다 확실하지만, 나는 이런 식으로 재 작성했다되지 않음 :

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

나에게 도움이되었다, 고마워! –

+0

나는 그것을 듣게되어 기쁘다. :) – SecondSun24