views:

197

answers:

2

I am trying to log in to my website (www.trailbehind.com) and then send a POST request to upload a file.

I tried implementing some code just to request the home page without authenticating, which I found here: http://developer.apple.com/documentation/Networking/Conceptual/CFNetwork/CFHTTPTasks/CFHTTPTasks.html#//apple_ref/doc/uid/TP30001132-CH5-DontLinkElementID_10

However, not even that code works, and I'm not sure what to do next. Here's the code I tried just to request the home page:

CFStringRef url = CFSTR("http://www.trailbehind.com/");
CFURLRef myURL = CFURLCreateWithString(kCFAllocatorDefault, url, NULL);
CFStringRef requestMethod = CFSTR("GET");
CFHTTPMessageRef myRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, requestMethod, myURL, kCFHTTPVersion1_1);

CFStringRef bodyData = CFSTR(""); // Usually used for POST data    
CFHTTPMessageSetBody(myRequest, bodyData);

CFStringRef headerFieldName = CFSTR("X-My-Favorite-Field");
CFStringRef headerFieldValue = CFSTR("Dreams");
CFHTTPMessageSetHeaderFieldValue(myRequest, headerFieldName, headerFieldValue);
CFDataRef mySerializedRequest = CFHTTPMessageCopySerializedMessage(myRequest);

//get the page
CFReadStreamRef myReadStream = CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, myRequest);
CFReadStreamOpen(myReadStream);

CFHTTPMessageRef myResponse = CFReadStreamCopyProperty(myReadStream, kCFStreamPropertyHTTPResponseHeader);
UInt32 myErrCode = CFHTTPMessageGetResponseStatusCode(myResponse);
NSLog(@"%@", myResponse);   

CFRelease(myRequest);
CFRelease(myURL);
CFRelease(url);
CFRelease(mySerializedRequest);
myRequest = NULL;
mySerializedRequest = NULL;
+1  A: 

You might want to take a look at my answer to a similar question about performing web requests here. The sample code shows how to use the NSURLRequest class to access a web resource. It's much easier than using the CF code :)

Daniel
+1  A: 

Take a look at ASIHTTPRequest. Very handy for quick-and-dirty HTTP work.

Ramin
After I read the other answerer's link, that's what I did. It was the accepted answer on that question, and on this one now as well :)
Andrew Johnson