http POST QuerIEs from Cocoa Applications Integrating web content with desktop applications. Part 3 in a 3-part serIEs
by Fritz Anderson
IntroductionIn the first two articles in this serIEs,we saw how easy it was to incorporate high-quality support for web content in Cocoa applications,so long as the request for the content Could be fully expressed in the URL. More sophisticated requests,embodIEd in http POST requests,are not directly available from the Cocoa API. Last month,we began exploring how to add such a facility to Cocoa,using the CFNetwork package of Core Foundation to build a formatted POST request.
This month,we will put what we've learned into an Objective-C class,that can be initialized with a URL,accept query parameters,present the query,and return the result.
As in the first two articles,our target web site will be Thomas,the library of Congress's database of legislative history,at http://thomas.loc.gov/. We'll build a little application that takes the number of a Congress (for instance the 107th Congress that sat 2001-02) and the name of a member of the House of Representatives,and displays a web page Listing all the measures that member sponsored.
Where we've BeenLast month's article already covered the use of Core Foundation's CFNetwork package to assemble and format a POST query. We saw how to marshal query parameters in an NSMutableDictionary,and how to marry the parameters and the necessary http headers into a query packet using a CFhttpMessage. The example code from last month resulted in an application that displayed the formatted query,ready for dispatch to a server.
CFNetwork also provIDes a powerful facility for dispatching the query once it's built,and receiving the results. This month,we'll build an Objective-C class,FAWebPOSTquery,around what we've already learned about building POST querIEs,and extend it so that getting web data from a POST can be as routine as the existing GET querIEs built into Cocoa.
Setting the Stagefigure 2 shows the Interface Builder connections for the human-interface sIDe of our test application. It's a tiny variation on the applications we've been building for the last two months--two fIElds for parameters,an NSTextVIEw for results,an NSbutton to set the query in motion,and,this time,an nsprogressIndicator to demonstrate that our program can do other things while the query is in-process. The Fetch button is wired to our controller object's doquery: method. The controller code--the clIEnt of our FAWebPOSTquery class--can be found in Listing 1.
The process of making a POST query can be divIDed into three parts: framing the query,posting the formatted query,and collecting the results. True to our plan,we find that doquery: consists of only two method calls--framequery and postquery.
Framing the query
The framequery method starts by harvesting the query parameters,and then creates the FAWebPostquery object. The object needs a URL for initialization,because an FAWebPostquery makes no sense without one,and optionally an NSDictionary of keys and values for the body of the query. As we dID last month,we marshal the parameters of the query in the query object. Parameters that never vary can be supplIEd through a constant NSDictionary,while parameters that Could differ with each query are set with the method setpoststring:forKey:. Because POST querIEs are key-value Lists,NSDictionary provIDes a natural analogy for specifying the body of the query. Using NSDictionary for initialization,and a method of the form set~:forKey: for management,was therefore an obvIoUs choice in API design.
Sending the query
POSTController's postquery method is even simpler: It sends the message post to the FAWebPostquery. That's it. The rest of the method sets an NSTimer to call our pendingTimer: method 20 times a second so we can run the nsprogressIndicator,and deactivates the Fetch button so we don't have to deal with more than one query at a time.
Receiving the Result
Now all the POSTController has to do is let the results roll in. FAWebPOSTquery relIEs on an informal protocol,that its delegate must implement the method webPostquery:completeDWithResult:. When the query has finished--successfully or not--FAWebPOSTquery returns the results and any result code to that method.
In the mean time,POSTController's timer method,and other methods on the UI thread,have been free to update the display and handle user events. So far as the user,and the code that uses FAWebPOSTquery is concerned,the query takes place completely in the background.
Behind the ScenesThat's what happens so far as our UI testbed--FAWebPostquery's clIEnt--is concerned. How is it done?
Last month we went over the issues in using CFhttpMessage to format the POST query. Readers of that article should find the init... and setpoststring:forKey: methods familiar,as well as the initial part of the post method,in which the CFhttpMessage is finished off and readIEd for sending.
We Could have the CFhttpMessage turn over its serialized bytes,send them directly,and handle the rest of the transaction ourselves,but there is a much neater mechanism available,an elaboration of CFStream,the Core Foundation implementation of the stream-of-bytes data type.
A CFReadStream or CFWriteStream,alone,is a routine sort of abstract data type: It allows you to do sequential buffered reads or writes on files,sockets,or memory using calls similar to the POSIX read(2) and write(2) functions. In this case,the CFReadStream we will be using will serve as a read descriptor returning the bytes of the body of the query response,but that is only one of four roles the CFReadStream will be playing.
The CFReadStream will
Send the query message to the server.Make callbacks to FAWebPostquery code when events occur.
Be a clIEnt of the application's run loop,to get a share of processor time to do its work.
YIEld bytes of the response to the query in response to a read call.
Each of these roles has to be initialized and (eventually) torn down.
Role 1: Sender of the query
The process starts with creating a CFReadStream for this transaction: replyStream = CFReadStreamCreateForhttpRequest( kcfAllocatorDefault,message); CFRelease(message); message = NulL;
Because the CFReadStream will be responsible for sending the POST query,the first thing we do is to associate the query message with the stream. At this point,FAWebPostquery has no further business with the query message,so it calls CFRelease to release its hold on it. This doesn't deallocate the message--the stream still retains a reference to it,and will release its reference later. The message will actually be sent when we call CFReadStreamopen().
Role 2: Sender of event callbacks
Next,we initialize the stream's role as a sender of event messages to the FAWebPostquery. The FAWebPostquery will want to kNow when data arrives in response to the query,and when the query transaction has finished--successfully or not.
BOol enqueued = CFReadStreamSetClIEnt(replyStream,kcfStreamEventHasBytesAvailable | kcfStreamEventErrorOccurred | kcfStreamEventEndEncountered,MyReadCallback,&cfContext);
CFReadStreamSetClIEnt tells our reply stream what events we are interested in; that we want our function MyReadCallback to be called when they happen; and that we want certain context information passed to the callback function.
If you've done much programming with APIs that make callbacks--for instance,the NSTimer and NSNotification mechanisms in Cocoa--you're familiar with the custom of provIDing a "user info" pointer in the setup of the callback. It's a way to pass a pointer to an object or other helpful context information into your callback handler. The last parameter of CFReadStreamSetClIEnt serves the same purpose,but instead of a simple generic pointer,this parameter must be a pointer to a CFStreamClIEntContext structure.
The reasoning behind this choice was this: The user info that you might want to pass through to a CFStream callback might be an ordinary pointer; it might be a reference-counted pointer to a Core Foundation object; or it might be a Cocoa object,which is also reference-counted,but by a different mechanism. The designers of the API decIDed that the CFStream should have a way to retain the user-info object if that is possible. (If you are done with the object,and the CFStream can retain and release it,you can release it immediately and not have the headache of guessing when it will be safe to release it later.) Therefore,you have to wrap the user-info pointer in a structure that includes pointers to functions that retain,release,and provIDe a CFString description of,the user-info data.
(Other Core Foundation APIs that define context structures allow you to pass NulL for the retain,and description function pointers if you do not want to define these operations. It is fair to assume the same rule applIEs to CFStreamClIEntContext,but at the time I write this,this part of the CFNetwork API had not yet been fully documented.)
FAWebPostquery passes itself as the user-info object,and therefore provIDes C wrappers to its inherited retain,and description methods. Listing 2 provIDes the whole story.
Role 3: Run loop clIEnt
Now we are ready to set the CFReadStream for its third role,as a clIEnt of the application run loop.
CFReadStreamScheduleWithRunLoop(replyStream,CFRunLoopGetCurrent(),kcfRunLoopCommonModes);
Veterans of Mac OS 9 and earlIEr are familiar with the event loop,the heart of a Macintosh program in the old operating system. At the head of the event loop is a call to WaitNextEvent(),which returns whenever user input or some other event occurs that the application must process; the rest of the loop is deVoted to IDentifying what part of the application should handle the event,and dispatching control to that handler.
Every thread under Core Foundation and Cocoa has an event loop of its own. At base,it's a CFRunLoop,which is not toll-free brIDged to the Cocoa NSRunLoop--you can get the underlying CFRunLoop from an NSRunLoop with the method getCFRunLoop. As with its Mac OS 9 cousin,it waits for events and dispatches them. Unlike the Mac OS 9 event loop,the details of the loop are hIDden; the task of calling handlers is done automatically; and the gamut of "events" that can be handled--timer events,driver events,UI events--is practically unlimited.
A CFRunLoop waits,without consuming cpu time,until an event occurs that one of its registered clIEnts can handle. Registered clIEnts can include CFRunLoopTimers (or their toll-free equivalents,NSTimers),whose events reflect the expiration of their timers; or I/O objects like our CFReadStream,whose events include the arrival of data,end-of-data,or a Fatal error. When the event occurs,the CFRunLoop calls the clIEnt's handler to respond to the event. In our case,CFReadStream will,in turn,call our callback function MyReadCallback. When the handler is done,control returns to the run loop,which returns to its sleep,waiting for the next event.
In this case,we register the reply stream with the current run loop. By specifying kcfRunLoopCommonModes,we ask that the stream's events be handled unless the event loop is put into a mode that explicitly restricts the handling of events. This is the usual way to register a run loop clIEnt.
With the call to CFReadStreamopen(),the query is under way,and the response arrives over the next few seconds. Against the possibility it doesn't arrive at all,we set a timeout timer:
timeoutTimer = [NSTimer scheduledTimerWithTimeInterval: sPostTimeout target: self selector: @selector(messageTimedOut:) userInfo: nil repeats: NO]; [timeoutTimer retain];
And,whenever the Thomas server gives evIDence that it is alive--by sending us data--we restart the timeout clock with:
[timeoutTimer setFireDate: [NSDate dateWithTimeIntervalSinceNow: sPostTimeout]];
Role 4: Read bytes from the stream
The remaining business of the FAWebPostquery object is to handle the events that come from the reply CFReadStream,all of which come to the callback function MyReadCallback. As you'd expect of an event handler,this function is built around a switch statement keyed on the type of event that arrived. Because we passed the FAWebPostquery object as the context when we registered the callback,we get it back as a voID* in the third parameter of the function.
When the event is kcfStreamEventHasBytesAvailable,the read stream finally fulfills the one task for which it is named:
UInt8 buffer[READ_SIZE]; CFIndex bytesRead = CFReadStreamRead(stream,buffer,READ_SIZE-1); // leave 1 byte for a trailing null. if (bytesRead > 0) { // Convert what was read to a C-string buffer[bytesRead] = 0; // Append it to the reply string [object appendContentCString: buffer]; }
Just as we would with a POSIX read() call,we pass the stream pointer,a buffer address,and the available length of the buffer to CFReadStreamRead. The number of bytes actually read is returned. Then the newly-arrived string can be appended to our results string.
Cleaning up
I decIDed to handle the other two events,kcfStreamEventErrorOccurred and kcfStreamEventEndEncountered in the same way. Either way,the query is over: All errors in CFReadStream handling are irrecoverable. In both cases,there are three tasks to complete: Harvest the last information the CFReadStream can yIEld; tear down the CFReadStream; and inform the clIEnt of the FAWebPostquery that the query has finished.
We've noticed before that http messages fall into two parts,header and body. The bytes returned to CFReadStreamRead while the response was read were,in fact,only the body of the response. The header of the response is kept as an attribute of the CFReadStream,and it is possible to get the response status code thus:
CFhttpMessageRef reply = (CFhttpMessageRef) CFReadStreamcopyProperty( replyStream,kcfStreamPropertyhttpResponseheader); // Pull the status code from the headers if (reply) { statusCode = CFhttpMessageGetResponseStatusCode(reply); CFRelease(reply); }
Now that we're done with the reply stream,we can release it from its varIoUs roles,and deallocate it. The first step is CFReadStreamClose(),which stops all further actions by the reply stream. Next,we tear down its role as a provIDer of callbacks to the FAWebPostquery object (and release any retains it might have done on the query object) by calling CFReadStreamSetClIEnt() with a NulL clIEnt value. Finally,we remove the reply stream from its role as a clIEnt to the run loop with CFReadStreamUnscheduleFromrunLoop(). The reply stream can Now be released with CFRelease().
ConclusionThose of us who met Cocoa for the first time in Mac OS X were amazed at the rich toolBox Apple laID at the feet of developers. The riches are still coming in the form of Core Foundation APIs like CFNetwork. Core Foundation can be daunting at first,but it's so well-designed that every Cocoa programmer should consIDer adding it to his repertoire.
Listing 1a: POSTController.h
//// POSTController.h// CocoaPOST//#import <Cocoa/Cocoa.h>@class FAWebPostquery;class POSTController@interface POSTController : NSObject { IBOutlet NSTextFIEld * membername; IBOutlet NSTextFIEld * congressFIEld; IBOutlet nsprogressIndicator * progress; IBOutlet NSbutton * fetchbutton; IBOutlet NSTextVIEw * resultText; FAWebPostquery * thequery; NSTimer * busyTimer;}- (IBAction) doquery: (ID) sender;- (voID) framequery;- (voID) postquery;- (voID) webPostquery: (FAWebPostquery *) query completeDWithResult: (int) code;- (voID) pendingTimer: (NSTimer *) aTimer;@end
Listing 1b: PostController.m
//// POSTController.m// CocoaPOST//#import "POSTController.h"#import "FAWebPostquery.h"sConstantDictionary,sThomasURLOnce initialized,these will be a dictionary and URL that constitute the parts of a member-name query that don't vary. The initialize class method will fill them in. They will be used in the framequery method to initialize new FAWebPostquery objects.static NSDictionary * sConstantDictionary = nil;static NSURL * sThomasURL = nil;class POSTController@implementation POSTControllerinitialize"Initialize" class methods are called automatically by the Objective-C runtime before any of the class's methods are executed. In this method,the static NSURL and NSDictionary that constitute the invariant parts of a Thomas query by member name are initialized.+ (voID) initialize{ if (! sConstantDictionary) { sConstantDictionary = [[NSDictionary alloc] initWithObjectsAndKeys: @"bimp",@"TYPE1",@"SPON",@"Sponfld",nil]; sThomasURL = [[NSURL alloc] initWithString: @"http://thomas.loc.gov/cgi-bin/bdquery"]; }}doqueryThis is the action method for the window's "Fetch" button. It initializes a new FAWebPostquery from the information entered in the window's fIElds,and then sends the query to the Thomas server.- (IBAction) doquery: (ID) sender{ [self framequery]; // Initialize the query [self postquery]; // Execute the query}stopTimerA convenIEnce method that checks to see if a query-pending timer is active,and if so,unschedules it from the run loop.- (voID) stopTimer{ if (busyTimer) { [busyTimer invalIDate]; busyTimer = nil; }}deallocThe standard release-of-resources handler for deallocation time.- (voID) dealloc{ [self stopTimer]; [thequery release];}framequeryHarvest the number of the Congress and the name of the Congressman from the respective fIElds,and initialize an FAWebPostquery to suit.- (voID) framequery{ int congress = [congressFIEld intValue]; Nsstring * member = [membername stringValue]; thequery = [[FAWebPostquery alloc] initWithServerURL: sThomasURL postData: sConstantDictionary]; [thequery setpoststring: [Nsstring stringWithFormat: @"d%d",congress] forKey: [Nsstring stringWithFormat: @"Dbd%d",congress]]; [thequery setpoststring: [Nsstring stringWithFormat: @"/bss/d%dquery.HTML",congress] forKey: @"srch"]; [thequery setpoststring: member forKey: @"HMEMB"]; [thequery setDelegate: self];}postqueryTells the FAWebPostquery we're done with preparation,and that it should send the query. We start an NSTimer to get periodic opportunitIEs to animate our progress indicator while the query is in progress. Finally,we deactivate the "Fetch" button,because I don't want to support multiple or interrupted querIEs.- (voID) postquery{ [thequery post]; busyTimer = [NSTimer scheduledTimerWithTimeInterval: 0.05 target: self selector: @selector(pendingTimer:) userInfo: nil repeats: YES]; [fetchbutton setEnabled: NO];}webPostquery:completeDWithResult:The query has completed. If it resulted in an error,inform the user. Otherwise,harvest the HTML in the reply and display it. This is the required method from the FAWebPostDelegate informal protocol.- (voID) webPostquery: (FAWebPostquery *) query completeDWithResult: (int) code{ [self stopTimer]; if (code == 200) { Nsstring * result = [thequery replyContent]; NSData * theHTML = [result dataUsingEnCoding: NSASCIIStringEnCoding]; NSAttributedString * styledText = [[NSAttributedString alloc] initWithHTML: theHTML documentAttributes: nil]; [[resultText textStorage] setAttributedString: styledText]; } [thequery release]; thequery = nil; [fetchbutton setEnabled: YES];}pendingTimer:The callback for the timer that this POSTController runs while awaiting completion of the query. It is here solely to run the progress bar,as a demonstration that the program is free to do other work while the query is being processed. The FAWebPostquery object keeps a timer of its own for timeouts on the query.- (voID) pendingTimer: (NSTimer *) aTimer{ [progress animate: nil];}@end
Listing 2a: FAWebPostquery.h
//// FAWebPostquery.h// Jefferson//#import <Foundation/Foundation.h>enum { FAWebPostIncomplete = -1,FAWebPostNotReplIEd = -2,FAWebPostReplyInProgress = -3,FAWebPostInvalID = -4,FAWebPostTimedOut = -5};FAWebPostAlreadyPostedAn exception that is thrown if an attempt is made to dispatch an FAWebPostquery that has already sent its query.extern Nsstring * const FAWebPostAlreadyPosted;class FAWebPostquery@interface FAWebPostquery : NSObject { CFhttpMessageRef message; CFReadStreamRef replyStream; NSMutableDictionary * postData; int statusCode; CFMutableStringRef cfReplyContent; NSTimer * timeoutTimer; NSObject * delegate; CFStreamClIEntContext cfContext;}- (ID) initWithServerURL: (NSURL *) server;- (ID) initWithServerURL: (NSURL *) server postData: (NSDictionary *) initialData;- (voID) setpoststring: (Nsstring *) string forKey: (Nsstring *) key;- (voID) post;- (voID) cancel;- (int) statusCode;- (Nsstring *) replyContent;- (NSObject *) delegate;- (voID) setDelegate: (NSObject *) aDelegate;@endFAWebPostDelegateThis is an informal protocol that must be implemented by any object that is passed to the setDelegate: method of an FAWebPostquery. It declares the signature of the callback message that is sent to the delegate object when the query either completes or fails.@interface NSObject (FAWebPostDelegate)- (voID) webPostquery: (FAWebPostquery *) query completeDWithResult: (int) code;@end
Listing 2b: FAWebPostquery.m
//// FAWebPostquery.m// Jefferson//#import "FAWebPostquery.h"#import "httpFlattening.h"#define READ_SIZE 1024Nsstring * const FAWebPostAlreadyPosted = @"FAWebPostAlreadyPosted";static CFTimeInterval sPostTimeout = 15.0;// A template for http stream-clIEnt contextsstatic CFStreamClIEntContext sContext = { 0,nil,CFClIEntRetain,CFClIEntRelease,CFClIEntDescribecopy}; class FAWebPostquery@implementation FAWebPostquerytimeoutIntervalA class method that returns the interval,in seconds,after which an http connection is consIDered to have timed out. When a query is posted,the reply must begin arriving within this time interval,and gaps between batches of data may not last longer. If the timer runs out,the connection is closed and the query fails with the error status FAWebPostTimedOut.+ (CFTimeInterval) timeoutInterval{ return sPostTimeout; }setTimeoutIntervalSets the length,for all timeout intervals beginning after this class method is called.+ (voID) setTimeoutInterval: (CFTimeInterval) newInterval{ sPostTimeout = newInterval;}CFClIEntRetainA glue function brIDging the Objective-C FAWebPostquery object to Core Foundation. A pointer to this function goes into the retain fIEld of the clIEnt context for the http CFStream that services the reply to the query.voID *CFClIEntRetain(voID * selfPtr){ FAWebPostquery * object = (FAWebPostquery *) selfPtr; return [object retain];}CFClIEntReleaseA glue function brIDging the Objective-C FAWebPostquery object to Core Foundation. A pointer to this function goes into the release fIEld of the clIEnt context for the http CFStream that services thereply to the query.voIDCFClIEntRelease(voID * selfPtr){ FAWebPostquery * object = (FAWebPostquery *) selfPtr; [object release];}CFClIEntDescribecopyA glue function brIDging the Objective-C FAWebPostquery object to Core Foundation. A pointer to this function goes into the copyDescription fIEld of the clIEnt context for the http CFStream that services the reply to the query.CFStringRefCFClIEntDescribecopy(voID * selfPtr){ FAWebPostquery * object = (FAWebPostquery *) selfPtr; return (CFStringRef) [[object description] retain];}getResultCodeAn internal-use method,called when the reply stream has indicated that it has either finished or experIEnced a Fatal error. RetrIEves the http header from the reply stream,if possible,and the http result code from the header. Sets the FAWebPostquery's status code to the result code.- (voID) getResultCode{ if (replyStream) { // Get the reply headers CFhttpMessageRef reply = (CFhttpMessageRef) CFReadStreamcopyProperty( replyStream,kcfStreamPropertyhttpResponseheader); // Pull the status code from the headers if (reply) { statusCode = CFhttpMessageGetResponseStatusCode(reply); CFRelease(reply); } }}cloSEOutMessagingAn internal-use method,called when the CFReadStream that manages the queery reply is no longer needed--either because the whole reply has been received or because the request has Failed. This method tears down the stream,the original POST query,and the timeout timer.- (voID) cloSEOutMessaging{ if (replyStream) { // Close the read stream. CFReadStreamClose(replyStream); // Deregister the callback clIEnt (learned this from WWDC session 805) CFReadStreamSetClIEnt(replyStream,NulL,NulL); // Take the stream out of the run loop CFReadStreamUnscheduleFromrunLoop( replyStream,kcfRunLoopCommonModes); // Deallocate the stream pointer CFRelease(replyStream); // Throw the spent pointer away replyStream = NulL; } if (timeoutTimer) { [timeoutTimer invalIDate]; [timeoutTimer release]; timeoutTimer = nil; }}informDelegateOfCompletionThis method gets called when the query has completed,successfully or not,after the network streams have been torn down. If this object's clIEnt has set a delegate,inform the delegate of completion through the method webPostquery:completeDWithResult:.- (voID) informDelegateOfCompletion{ if (delegate) { NSAssert( [delegate respondsToSelector: @selector(webPostquery:completeDWithResult:)],@"A web-POST query delegate must implement " @"webPostquery:completeDWithResult:"); [delegate webPostquery: self completeDWithResult: statusCode]; }}appendContentCString:An internal method called by MyReadCallback. It appends the C string it is passed to the CFMutableString that keeps the body of the reply to the query. Passing this message sets this object's status to in-progress,and restarts the timeout timer.- (voID) appendContentCString: (char *) cString{ CFStringAppendCString(cfReplyContent,cString,kcfStringEnCodingASCII);statusCode = FAWebPostReplyInProgress; // Refresh the timeout timer. [timeoutTimer setFireDate: [NSDate dateWithTimeIntervalSinceNow: sPostTimeout]];}MyReadCallbackThis is the registered event callback for the CFReadStream that manages sending the query and receiving the reply. If data has arrived in the reply,the data is taken from the stream and accumulated. If the transaction ends because of error or success,a final result code is set,the CFReadStream is torn down,and the registered clIEnt,if any is informed.voIDMyReadCallback(CFReadStreamRef stream,CFStreamEventType type,voID * userData){ FAWebPostquery * object = (FAWebPostquery *) userData; switch (type) { case kcfStreamEventHasBytesAvailable: { UInt8 buffer[READ_SIZE]; CFIndex bytesRead = CFReadStreamRead(stream,READ_SIZE-1); // leave 1 byte for a trailing null. if (bytesRead > 0) { // Convert what was read to a C-string buffer[bytesRead] = 0; // Append it to the reply string [object appendContentCString: buffer]; } } break; case kcfStreamEventErrorOccurred: case kcfStreamEventEndEncountered: [object getResultCode]; [object cloSEOutMessaging]; [object informDelegateOfCompletion]; break; default: break; }}messageTimedOut:The callback for the internal timeout timer. This method gets called only in the exceptional case of the Remote Server not responding within the specifIEd time. It's a Fatal error,and causes the connection to be torn down and the delegate (if any) notifIEd.- (voID) messageTimedOut: (NSTimer *) theTimer{ statusCode = FAWebPostTimedOut; [self cloSEOutMessaging]; [self informDelegateOfCompletion];}- (ID) initWithServerURL: (NSURL *) server{ return [self initWithServerURL: server postData: nil];}- (ID) initWithServerURL: (NSURL *) server postData: (NSDictionary *) initialData{ replyStream = NulL; cfReplyContent = CFStringCreateMutable( kcfAllocatorDefault,0); statusCode = FAWebPostIncomplete; cfContext = sContext; cfContext.info = self; timeoutTimer = nil; if (initialData) postData = [[NSMutableDictionary alloc] initWithDictionary: initialData]; else postData = [[NSMutableDictionary alloc] initWithCapacity: 8]; if (!postData) { [self release]; return nil; } // Set up the POST message and its headers message = CFhttpMessageCreateRequest( kcfAllocatorDefault,CFSTR("POST"),(CFURLRef) server,kcfhttpVersion1_1); if (!message) { [self release]; return nil; } CFhttpMessageSetheaderFIEldValue(message,CFSTR("User-Agent"),CFSTR("Generic/1.0 (Mac_PowerPC)")); CFhttpMessageSetheaderFIEldValue(message,CFSTR("Content-Type"),CFSTR("application/x-www-form-urlencoded")); CFhttpMessageSetheaderFIEldValue(message,CFSTR("Host"),(CFStringRef) [server host]); CFhttpMessageSetheaderFIEldValue(message,CFSTR("Accept"),CFSTR("text/HTML")); return self;}- (voID) setpoststring: (Nsstring *) string forKey: (Nsstring *) key{ [postData setobject: string forKey: key];}- (voID) dealloc{ if (message) { CFRelease(message); message = NulL; } [postData release]; if (cfReplyContent) { CFRelease(cfReplyContent); cfReplyContent = NulL; } if (timeoutTimer) { [timeoutTimer invalIDate]; [timeoutTimer dealloc]; timeoutTimer = nil; }}- (voID) post{ if (statusCode != FAWebPostIncomplete) [NSException raise: FAWebPostAlreadyPosted format: @"This query has already been posted " @"and either answered or refused."]; statusCode = FAWebPostNotReplIEd; // String-out the postData dictionary Nsstring * poststring = [postData webFormEncoded]; NSData * poststringData = [poststring dataUsingEnCoding: kcfStringEnCodingASCII allowLossyConversion: YES]; // Put the post data in the body of the query CFhttpMessageSetbody(message,(CFDataRef) poststringData); // Now that we kNow how long the query body is,put the length in the header CFhttpMessageSetheaderFIEldValue(message,CFSTR("Content-Length"),(CFStringRef) [Nsstring stringWithFormat: @"%d",[poststringData length]]); // Initialize the CFReadStream that will make the request and manage the reply replyStream = CFReadStreamCreateForhttpRequest( kcfAllocatorDefault,message); // I have no further business with message CFRelease(message); message = NulL; // Register the CFReadStream's callback clIEnt BOol enqueued = CFReadStreamSetClIEnt(replyStream,kcfStreamEventHasBytesAvailable | kcfStreamEventErrorOccurred | kcfStreamEventEndEncountered,&cfContext); // Schedule the CFReadStream for service by the current run loop CFReadStreamScheduleWithRunLoop(replyStream,kcfRunLoopCommonModes); // Fire off the request CFReadStreamOpen(replyStream); // Watch for timeout timeoutTimer = [NSTimer scheduledTimerWithTimeInterval: sPostTimeout target: self selector: @selector(messageTimedOut:) userInfo: nil repeats: NO]; [timeoutTimer retain];}- (voID) cancel{ NSAssert(replyStream,@"The program should prevent cancelling " @"when no query is in progress."); [self cloSEOutMessaging]; statusCode = FAWebPostInvalID;}- (int) statusCode { return statusCode; }- (Nsstring *) replyContent { return (Nsstring *) cfReplyContent;}- (NSObject *) delegate { return delegate; }- (voID) setDelegate: (NSObject *) aDelegate{ delegate = aDelegate; }@end总结
以上是内存溢出为你收集整理的HTTP POST Queries from Cocoa Applications全部内容,希望文章能够帮你解决HTTP POST Queries from Cocoa Applications所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)