如何使用HttpURLConnection获取重定向的URL和内容 [英] How to get redirected URL and content using HttpURLConnection

查看:143
本文介绍了如何使用HttpURLConnection获取重定向的URL和内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时我的网址会重定向到新网页,所以我想获取新网页的网址。

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

这是我的代码:

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

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

输出为:


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

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

It适用于Stack Overflow网站,但对于sears.com网站,它不起作用。

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

如果我们输入URL打击:

If we enter the URL blow:

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

输出仍然是:


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?

推荐答案

实际上我们可以使用HttpClient,我们可以设置HttpClient.followRedirect(true)
HttpClinent将处理重定向的事情。

actually we can use HttpClient, which we can set HttpClient.followRedirect(true) HttpClinent will handle the redirect things.

这篇关于如何使用HttpURLConnection获取重定向的URL和内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆