Android奇怪的URL获取

发布于 2024-10-16 18:14:23 字数 421 浏览 6 评论 0原文

我这里有一个奇怪的问题。这是我用来获取网址内容的代码:

URL u = new URL(url);
InputStream is = new BufferedInputStream(u.openStream());

我有两个网址,我想用此代码获取。两者都包含 xml 数据。具体来说,第一个是http://www.berlingske.dk/unwire/latest/news_article/2/10,第二个是http://www.bt。 dk/mecommobile/latest/news_article/1368/10?output_type=xml。第一个被正确获取,第二个则没有。我添加了一些日志记录,发现对于第二个 url,会获取一些奇怪的 html 页面,而不是预期的 xml。这怎么可能?

I'm having a strange problem here. Here's the code, I'm using to fetch a url content:

URL u = new URL(url);
InputStream is = new BufferedInputStream(u.openStream());

I've got two urls, I want to fetch with this code. Both contain xml data. To be specific, the first one is http://www.berlingske.dk/unwire/latest/news_article/2/10, the second one is http://www.bt.dk/mecommobile/latest/news_article/1368/10?output_type=xml. The first one gets fetched correctly, the second one does not. I added some logging, and found out, that for the second url some weird html page gets fetched, instead of the expected xml. How can that be even possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

青衫儰鉨ミ守葔 2024-10-23 18:14:23

我认为您正在谈论 URL 重定向,这是我遇到的问题。尝试以下代码:

URL url = new URL(url);
HttpURLConnection ucon = (HttpURLConnection) url.openConnection();
ucon.setInstanceFollowRedirects(false);
URL secondURL = new URL(ucon.getHeaderField("Location"));
URLConnection conn = secondURL.openConnection();
InputStream is = new BufferedInputStream(conn.openStream());

这里的“魔法”发生在以下两个步骤中:

ucon.setInstanceFollowRedirects(false);
URL secondURL = new URL(ucon.getHeaderField("Location"));

默认情况下 InstanceFollowRedirects 设置为 true,但您希望将其设置为 false 以捕获第二个 url。为了能够从“奇怪的 html 页面”获取第二个 url,您需要获取名为 “Location” 的标头字段。

除非我误解了你的问题,否则我希望这会有所帮助!

I think you're talking about URL redirects, which was a problem I was having. Try the following code:

URL url = new URL(url);
HttpURLConnection ucon = (HttpURLConnection) url.openConnection();
ucon.setInstanceFollowRedirects(false);
URL secondURL = new URL(ucon.getHeaderField("Location"));
URLConnection conn = secondURL.openConnection();
InputStream is = new BufferedInputStream(conn.openStream());

The "magic" here happens in these 2 steps:

ucon.setInstanceFollowRedirects(false);
URL secondURL = new URL(ucon.getHeaderField("Location"));

By default InstanceFollowRedirects are set to true, but you want to set it to false to capture the second url. To be able to get that second url from the "weird html page", you need to get the header field called "Location".

Unless i misunderstood your problem, I hope this helps!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文