Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

java - How to get redirected URL and content using HttpURLConnection

Sometimes my URL will redirect to a new page, so I want to get the URL of the new page.

Here is my code:

URL url = new URL("http://stackoverflow.com/questions/88326/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setInstanceFollowRedirects(true);

System.out.println(conn.getURL().toString());

The output is:

stackoverflow.com/questions/88326/does-elmah-handle-caught-exceptions-as-well

It works well for the Stack Overflow website, but for the sears.com site, it doesn't work.

If we enter the URL blow:

http://www.sears.com/search=iphone

the output is still:

http://www.sears.com/search=iphone

But actually, the page will redirect to:

http://www.sears.com/tvs-electronics-phones-all-cell-phones/s-1231477012?keyword=iphone&autoRedirect=true&viewItems=25&redirectType=CAT_REC_PRED

How can I solve this problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Simply call getUrl() on URLConnection instance after calling getInputStream():

URLConnection con = new URL(url).openConnection();
System.out.println("Orignal URL: " + con.getURL());
con.connect();
System.out.println("Connected URL: " + con.getURL());
InputStream is = con.getInputStream();
System.out.println("Redirected URL: " + con.getURL());
is.close();

If you need to know whether the redirection happened before actually getting it's contents, here is the sample code:

HttpURLConnection con = (HttpURLConnection) (new URL(url).openConnection());
con.setInstanceFollowRedirects(false);
con.connect();
int responseCode = con.getResponseCode();
System.out.println(responseCode);
String location = con.getHeaderField("Location");
System.out.println(location);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...