سؤال

I'm confused a litle bit about URLConnection.connect() and URL.openConnection(), from official Java docs it says that URL.openConnection() returns only URLConnection instance but not already opened connection so I must call URLConnection.connect() somewhere further in code, but in Android tutorials http://developer.android.com/reference/java/net/URLConnection.html URLConnection.connect() wasn't called. So is a URLConnection.getInputStream establishes a connection too? And when I should call connect() method?

هل كانت مفيدة؟

المحلول

AFAIK it's useless to call connect(). Maybe by calling this the state of the HUC changes from CREATED to CONNECTED. But in all docs I've read it is sayed that it doesn't hurt to call connect() and it's ignored if you're already connected.

So in fact, when you call a method like getInputStream(), getContentLength(), getOutputStream(), the connection will be established to the server if it is not already done.

But one thing is often used wrong IMO: in many code samples you can see that getInputStream() is called before getResponseCode(). I've observed that getInputStream() throws an Exception when you call it in case of HTTP status code >= 400.

So I recommend doing it this way (pseudo-code):

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())

You can read the whole (more involved) code here.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top