Database Reference
In-Depth Information
This version, if passed the same data as we used before, produces identical XML. So
why go to the trouble of building up all those DOM structures when a simple format
will do? Well, one reason is that using DOM makes sure that you don't leave out a
quotation mark or angle bracket, or forget an end tag, producing bad XML.
But there's a much more important reason, which is the same reason you never use
format strings to create SQL statements, it's too easy to inject garbage into the payload.
Let's compare the two methods again, but with slightly more complex data (newlines
and indents have been added to improve readability):
By Format:
<newsitem postdate="2011-07-26" posttime="11:23">
<subject>This is a test subject<subject>
<body>
Buggy whips are cool & neat, > all the rest, aren't they?
</body>
</newsitem>
By DOM:
<newsitem postdate="2011-07-26" posttime="11:23">
<subject>This is a test subject</subject>
<body>
Buggy whips are cool &amp; neat, &gt; all the rest, aren't they?
</body>
</newsitem>
Oh my, look at all the illegal XML characters in the middle of our payload, just waiting
to break any innocent XML parser waiting on the other end. By contrast, the example
using DOM construction has appropriately escaped any dangerous content.
The decision as to whether to use formatting or DOM construction isn't absolute. If
you have good control of the data you're sending, and can be absolutely sure that no
XML-invalid characters will be contained inside the parameters, formatting can be a
real time- and code-saver. But it is inherently more dangerous than using a DOM, and
you also have to deal with pesky problems such as escaping all your quote signs. I've
used both techniques where appropriate, but I'm starting to lean more heavily toward
DOM construction these days.
One last item: once you have the XML, how do you send it in a POST? The code is
fairly simple; it's almost identical to the NSURLConnection code to do a GET. An
example can be seen in Example 4-9 .
Example 4-9. Posting data using NSURLConnection
-(void) sendNewsToServer:(NSString *) payload {
NSURL *url = [NSURL URLWithString:@"http://thisis.a.bogus/url"];
NSMutableURLRequest *request = [NSMutableURLRequest
requestWithURL:url];
[request setHTTPMethod:@"POST"];
NSMutableDictionary *headers =
[NSMutableDictionary dictionaryWithDictionary:[request allHTTPHeaderFields]];
[headers setValue:@"text/xml" forKey:@"Content-Type"];
 
Search WWH ::




Custom Search