Android InputStream 遵循重写规则
我正在尝试从网站解析 xml 文件。假设该网站是“http://example.com”
该网站有一个 htaccess 重写规则设置,用于重定向任何内容将主机的“www”前缀返回到 example.com。因此“http://www.example.com”将重定向到“http://example.com"
在我的代码中,我有一个获取 InputStream 的 URL。
protected InputStream getInputStream() {
try {
return feedUrl.openConnection().getInputStream();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
在这种情况下, feedUrl 指向“http://www.example.com/file.xml”,当我执行以下操作时:
try {
Xml.parse(this.getInputStream(), Xml.Encoding.UTF_8, root.getContentHandler());
} catch (Exception e) {
throw new RuntimeException(e);
}
我抛出异常,并且我相信它没有重定向到“http:// example.com/file.xml"
显然,我可以静态地更改 feedUrl 变量指向的位置,但我需要它是动态的。
I'm trying to parse an xml file from a website. Let's say the website is "http://example.com"
This website has a htaccess rewrite rule setup to redirect anything with a "www" prefix to the host back to example.com. so "http://www.example.com" would redirect to "http://example.com"
In my code I have a URL that i get the InputStream of.
protected InputStream getInputStream() {
try {
return feedUrl.openConnection().getInputStream();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
In this case feedUrl is poingting to "http://www.example.com/file.xml" and when I do the following:
try {
Xml.parse(this.getInputStream(), Xml.Encoding.UTF_8, root.getContentHandler());
} catch (Exception e) {
throw new RuntimeException(e);
}
I get an exception thrown and I believe it's not redirecting to "http://example.com/file.xml"
I could obviously just statically change where my feedUrl variable is pointing to, but I need this to be dynamic.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果有人像我一样遇到这个问题,那么这就是解决方案。如果响应代码为 300、301、302 或 303,HttpURLConnection 已设置为默认遵循重定向。
出于某种原因,我解析的服务器需要将响应代码设置为 307,而 Android 不会自动重定向。
我建议使用不同的响应代码,但如果您的服务器需要它,那么这里有解决方法。
现在 conn 可以打开正确文件的输入流。
If anyone ran into this problem like I did, then here's the solution. The HttpURLConnection is already setup to follow redirects by default if the response code is 300, 301, 302, or 303.
For some reason, the server I'm parsing from needs to have the response code be 307 which Android does not redirect automatically.
I would suggest using a different response code, but if your server needs it then here's work around.
Now conn can open an input stream to the correct file.