Execute a POST request
// target URL
CFURLRef URL = CFURLCreateWithString(
kCFAllocatorDefault,
CFSTR("http://www.apple.com"),
NULL);
// request type
CFStringRef requestMethod =
CFSTR("POST");
// setup request
CFHTTPMessageRef myRequest =
CFHTTPMessageCreateRequest(
kCFAllocatorDefault,
requestMethod,
URL,
kCFHTTPVersion1_1);
// body
CFStringRef bodyString =
CFSTR("[[post content value-pairs]]");
// set body in msg
CFHTTPMessageSetBody(
myRequest,
CFStringCreateExternalRepresentation(
NULL,
bodyString,
kCFStringEncodingMacRoman,
'?'));
// header
CFHTTPMessageSetHeaderFieldValue(
myRequest,
CFSTR("Content-Length"),
(CFStringRef) [NSString stringWithFormat: @"%d",
CFStringGetLength(bodyString)]);
// header property #1
CFHTTPMessageSetHeaderFieldValue(
myRequest,
CFSTR("Host"),
CFSTR("www.apple.com"));
// header property #2
CFHTTPMessageSetHeaderFieldValue(
myRequest,
CFSTR("Content-Type"),
CFSTR("application/x-www-form-urlencoded"));
// POST it
CFReadStreamRef myReadStream =
CFReadStreamCreateForHTTPRequest(
kCFAllocatorDefault,
myRequest);
CFStreamClientContext myContext =
{ 0, (void*)NULL, NULL, NULL, NULL };
CFReadStreamSetProperty(
myReadStream,
kCFStreamPropertyHTTPAttemptPersistentConnection,
kCFBooleanTrue);
CFReadStreamSetClient(
myReadStream,
kCFStreamEventHasBytesAvailable |
kCFStreamEventErrorOccurred |
kCFStreamEventEndEncountered,
ReadStreamClientCallBack,
&myContext);
CFReadStreamScheduleWithRunLoop(
myReadStream,
CFRunLoopGetCurrent(),
kCFRunLoopCommonModes);
CFReadStreamOpen(myReadStream);
CFRelease(myRequest);
CFRelease(URL);
Access the message returned
// debug print message
CFDataRef msgFromRequest =
CFHTTPMessageCopySerializedMessage(myRequest);
// length of msg
int msgLength =
CFDataGetLength(msgFromRequest);
// buffer to hold data
Byte* buffer =
(Byte*) malloc (sizeof(Byte) * msgLength);
// grab data place into buffer
CFDataGetBytes(msgFromRequest, CFRangeMake(0, msgLength), buffer);
// clean up
CFRelease(msgFromRequest);
free(buffer);
1 comment:
hey thanks a ton!!! this stuff really helped me out.
Post a Comment