【问题标题】:URLConnection.getContent with HTML file带有 HTML 文件的 URLConnection.getContent
【发布时间】:2012-07-13 03:30:03
【问题描述】:

当我使用类似的东西时:

URL url = new URL(a_url);
URLConnection url_conn = url.openConnection();
Object content = url_conn.getContent();

并且检索到的文件的 MIME 类型是我调试过的 HTML 或 XML content 在运行时将包含以下实例:

sun.net.www.protocol.http.HttpURLConnection$HttpInputStream

现在,如果我想在该实例上使用 instanceof,我该怎么办?

if (content instanceof PlainTextInputStream)
{
...
}  
else if(content instanceof ImageProducer)
{
...
}
else if(content instanceof ???) {}

【问题讨论】:

  • 为什么?您只需要内容类型和数据。内容类型在标头中:数据在输入流中。您根本不必询问输入流类。
  • 是的,谢谢,我会这样做,但是,目前,仅出于教育目的,如何实例化像 sun.net.www.protocol.http.HttpURLConnection$HttpInputStream 这样的嵌套类?

标签: java servlets httpurlconnection


【解决方案1】:

你不应该依赖于实现类。总有一天会坏的。

我认为您应该根据请求标头这样做:

URLConnection url_conn = url.openConnection();
httpURLConnection http_url_conn = (httpURLConnection )url.openConnection();

String contentType = http_url_conn.getContentType()

  if(contentType.contains("text/plain")){
    //handle plain text
    .....
  } else if(contentType.contains("images/jpeg")){
    //handle image
    ......
  } 

在此处阅读有关 Content-Type 的更多信息:

【讨论】:

  • 是的,谢谢,这也是一个很好的解决方案。但是我想知道如何访问那种类型......也许是这样的? content.getClass().toString().equals("class sun.net.www.protocol.http.HttpURLConnection$HttpInputStream")
  • 实现类可以随时更改。不是一个好习惯。
猜你喜欢
  • 2014-11-11
  • 2017-01-21
  • 1970-01-01
  • 2020-09-17
  • 2018-03-03
  • 2019-03-29
  • 1970-01-01
  • 2013-10-21
  • 2018-12-05
相关资源
最近更新 更多