HTTP GET by CFNetwork

24 02 2008

I came across the same problem described in fraserspeirs: HTTP Nerdery, or, Why NSURLConnection Sucks For POST.I tried to send POST reqeust to a HTTP server with NSURLRequest and NSURLConnection, but nothing sent.

So I decided to use CFNetwork instead.Here is my first attempt. Because this code blocks until the server returns HTTP response, I’m modifying to non-blocking version which make use of “Run Loops”.

CFURLRef url = CFURLCreateWithString(NULL, CFSTR("http://www.google.co.jp/"), NULL);
CFHTTPMessageRef httpRequest = CFHTTPMessageCreateRequest(NULL, CFSTR("GET"), url, kCFHTTPVersion1_1);
CFReadStreamRef readStream = CFReadStreamCreateForHTTPRequest(NULL, httpRequest);
CFReadStreamOpen(readStream);

CFIndex bytes;
int bufSize = 1024;
UInt8 buf[bufSize];

do {
    bytes = CFReadStreamRead(readStream, buf, sizeof(buf));
    if( bytes > 0 ){
        NSString *responseString = [[NSString alloc] initWithBytes:buf length:bytes encoding:NSUTF8StringEncoding];
        NSLog(responseString);
    } else if( bytes < 0 ) {
        CFStreamError error = CFReadStreamGetError(readStream);
    }
} while( bytes > 0 );

CFHTTPMessageRef httpResponse = (CFHTTPMessageRef)CFReadStreamCopyProperty(readStream, kCFStreamPropertyHTTPResponseHeader);

if(httpResponse) {
    CFStringRef responseStatus = CFHTTPMessageCopyResponseStatusLine(httpResponse);
    NSLog((NSString *)responseStatus);
}

Actions

Information

4 responses

24 02 2008
Peter Hosey

Presentation bug: Your code is all on one line, making it really hard to read.

24 02 2008
Peter Hosey

Also, remember to Release everything you Create.

24 02 2008
Peter Hosey

One more thing: Fraser Speirs started out doing GET, then switched to POST. As he says in his post, GET worked just fine—it’s POST that he had a problem with.

Your code demonstrates GET, not POST.

24 02 2008
jgoamakf

Peter, thanks for pointing out. I think it fixed now.

I found that there are cases when wordpress strips my line break. I’m experimenting wordpress editor and settings so that this never happen again.

The code is work-in-progress. I’ll create another entry or modify here when I succeed in sending POST request to the server which I actually want to communicate with.

When doing GET request, NSURLConnection works well in my case, too.

Leave a comment