2011-09-14 3 views
4

나는 사용하여 웹 페이지 A의 내용을 추출하려고 끝내 내가 해봤 위의 코드는 한 그것이 다른 웹 페이지로 리디렉션하지 않는 웹 페이지 (A)의 텍스트를 검색페이지 URL이 리디렉션되는 경우 프로그램 방식으로 확인하는 방법은 무엇입니까?

...... 
String urlStr = "url-of-webpage-A" 
String pageText = urlStr.toURL().text 
//println pageText 
..... 

다음 B. A가 B로 리디렉션되면 webPage B의 페이지 내용이 pageText 변수에서 검색됩니다. 웹 페이지 A가 다른 웹 페이지 (groovy 또는 java)로 리디렉션되는지 코드하고 확인하는 방법이 있습니까?

PS : 위의 코드 부분은 서버 측 로직의 일부가 아니다. 클라이언트 측에서 데스크톱 응용 프로그램의 범위 내에서 실행하고 있습니다.

답변

4

, 당신은 무엇을 Joachim suggests 수행하여 할 수있는 :

을 : 당신이 리디렉션하려면, 첫 페이지의 내용을 원하지 않는 경우

String location = "url-of-webpage-A" 
boolean wasRedirected = false 
String pageContent = null 

while(location) { 
    new URL(location).openConnection().with { con -> 
    // We'll do redirects ourselves 
    con.instanceFollowRedirects = false 

    // Get the response code, and the location to jump to (in case of a redirect) 
    location = con.getHeaderField("Location") 
    if(!wasRedirected && location) { 
     wasRedirected = true 
    } 

    // Read the HTML and close the inputstream 
    pageContent = con.inputStream.withReader { it.text } 
    } 
} 

println "wasRedirected:$wasRedirected contentLength:${pageContent.length()}" 

, 당신은 간단하게 할 필요가

String location = "url-of-webpage-A" 
String pageContent = new URL(location).openConnection().with { con -> 
    // We'll do redirects ourselves 
    con.instanceFollowRedirects = false 

    // Get the location to jump to (in case of a redirect) 
    location = con.getHeaderField("Location") 

    // Read the HTML and close the inputstream 
    con.inputStream.withReader { it.text } 
} 

if(location) { 
    println "Page wanted to redirect to $location" 
} 
println "Content was:" 
println pageContent  
+0

안녕하세요 팀, 나는 위의 코드를 시도했지만 여전히 새로운 위치/리디렉션 된 웹 페이지의 내용을 검색합니다. :(원본 페이지의 내용이 필요합니다. –

+1

@VeeKay 오 ... 최종 페이지의 내용을 원했지만 리디렉션되었음을 알았습니다 ... 희망하는 일을하기 위해 다른 방법을 추가했습니다. 당신이 원했던 ... –

14

자바에서 당신이 얻을 수 URL.openConnection()를 사용할 수있는 HttpURLConnection (당신이 캐스팅해야합니다). 이것에 setInstanceFollowRedirects(false)를 부를 수있다.

(301), HTTP_MOVED_TEMP (302) 또는 HTTP_SEE_OTHER (303)인지 확인하십시오. 모두 리디렉션을 나타냅니다.

을 알아야 할 경우으로 리디렉션되는 경우 getHeaderField("Location")을 사용하여 위치 헤더를 가져올 수 있습니다. 그루비에서

관련 문제