【问题标题】:URLConnection opening weirdnessURLConnection 打开怪异
【发布时间】:2016-04-12 05:22:22
【问题描述】:

很难理解 URLConnection 以及可能在哪里隐式调用 connect()。

此代码不起作用:

URL url = new URL(firstUrl);
HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
conn.getHeaderField("Location"); //returns null
connection.setInstanceFollowRedirects(false);

此代码有效:

URL url = new URL(firstUrl);
HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
connection.setInstanceFollowRedirects(false);
conn.getHeaderField("Location"); //returns the redirect URL

我很难理解这一点。 “getHeaderField”是否隐式调用连接?我在任何地方的文档中都没有看到这一点。

【问题讨论】:

    标签: java http url httpurlconnection


    【解决方案1】:

    【讨论】:

    • 啊,所以“getInputStream”打开了连接?
    • @cjcamisa 任何需要(部分)服务器响应的东西都会隐式执行.connect。这包括用于正文的getContent/getInputStream/getErrorStream 和用于标题的getHeaderField/getContentType/etc。查看页面顶部和connect()下的parentdocs.oracle.com/javase/8/docs/api/java/net/URLConnection.html
    猜你喜欢
    • 1970-01-01
    • 2015-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多