Hello, all ...
I'm trying to make my app handle HTTP authentication, and i'm running into problems. Right now, i'm just trying to get the HTTP status code of the response, and CFReadStreamCopyProperty() is returning NULL:
The URL is: http://he3.magnatune.com/all/01--Tensor--Chris %20Harvey.mp3 (verified to work in Safari on my Mac). This is what i'm trying to do:
CFHTTPMessageRef message= CFHTTPMessageCreateRequest(NULL, (CFStringRef)@"GET", (CFURLRef)url, kCFHTTPVersion1_1);
CFHTTPMessageSetHeaderFieldValue(message, CFSTR("User-Agent"), CFSTR("My user agent"));
stream = CFReadStreamCreateForHTTPRequest(NULL, message);
if (CFReadStreamOpen(stream))
{
CFHTTPMessageRef myResponse = CFReadStreamCopyProperty(stream, kCFStreamPropertyHTTPResponseHeader);
int resStatus = CFHTTPMessageGetResponseStatusCode(myResponse); // crashes here because myResponse is NULL
.
.
.
}
The platform is iPhone OS 2.2.1, if that helps. The Apple documentation for CFReadStreamCopyProperty() doesn't say anything about why it might return NULL. Furthermore, if I comment out the code trying to get the response, the rest of the code works and I get the data from the URL. What am I doing wrong?
Regards,
John
Falling You - exploring the beauty of voice and sound
-------------------------------------------------------------------------------------------------------------------------
Jens,
I would guess that you can't access the response data until the stream has connected and read data. I'm not sure about the concurrency model of CFReadStream used with HTTP messages; it might be asynchronous, or you might have to tell it to read first.
I thought that CFReadStreamOpen() did that? I guess not, at least in this case, so i'll look into that ...
But the higher level question is, why are you using such a low-level API instead of NSURLConnection? The latter will make your life much easier, and it supports more HTTP features too, like redirects.
NSURLConnection caches data and doesn't let me, the developer, control how much I read from the socket. This led to huge memory usage in my iPhone app, as NSURLConnection would happily read way ahead into the stream and cache it, causing the iPhone OS to send my app low memory warnings. Moving to a CFNetwork-based solution let me control when and how much I read from the stream, and it fixed the memory issues I was having.
The downside is that, while NSURLConnection handled all of this stuff for me, I now have to do it myself. It's worth it to me, though :-)
Regards,