【问题标题】:For what reasons i should call UrlConnection.connect()出于什么原因我应该调用 UrlConnection.connect()
【发布时间】:2014-03-18 02:24:31
【问题描述】:

我对@9​​87654323@ 和URL.openConnection() 有点困惑,官方Java 文档中说URL.openConnection() 只返回URLConnection 实例但尚未打开连接,所以我必须在更远的地方调用URLConnection.connect()代码,但在 Android 教程中 http://developer.android.com/reference/java/net/URLConnection.html URLConnection.connect() 没有被调用。那么URLConnection.getInputStream 是否也建立了连接?什么时候应该调用 connect() 方法?

【问题讨论】:

标签: android url httpurlconnection


【解决方案1】:

AFAIK 打电话给connect() 是没用的。也许通过调用这个 HUC 的状态从 CREATED 变为 CONNECTED。但在我读过的所有文档中,都说拨打connect() 并没有什么坏处,如果你已经连接,它会被忽略。

所以实际上,当你调用getInputStream()getContentLength()getOutputStream() 之类的方法时,如果尚未建立与服务器的连接。

但是 IMO 经常用错一件事:在许多代码示例中,您可以看到 getInputStream()getResponseCode() 之前被调用。我观察到getInputStream() 在 HTTP 状态代码 >= 400 的情况下调用它时会引发异常。

所以我建议这样做(伪代码):

if (method == POST || method == PUT)
    con.setDoOutput(true)
    writeBody(con)

statusCode = con.getResponseCode()

if (statusCode is successful)
    readStream(con.getInputStream())
else
    // if you expect some information in the body in case of error...
    readStream(con.getErrorStream())

您可以阅读整个(更多涉及的)代码here

【讨论】:

    猜你喜欢
    • 2011-08-16
    • 2020-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-09
    • 2023-03-28
    • 2022-07-09
    相关资源
    最近更新 更多