Vladyslav Elashevskyy
Vladyslav Elashevskyy

Reputation: 23

post variable containing XML data to a web-server using POST in iPhone

I've looked through a lot of opened questions within similar topic but unfortunately couldn't find the answer. The thing is I'm new to sending POST/GET messages and I'm not sure How do I need to POST variable containing XML data to a web-server.

"Use POST or GET variable "test" with XML string on a specified URL".

I know how to make connection, and put XML into HTTPBody and make a request. But I don't know how to specify XML for a variable.

Please help.

Upvotes: 2

Views: 1131

Answers (1)

carlossless
carlossless

Reputation: 1181

If by "specify XML for a variable" you mean send an XML string as part of multipart/form-data, then it's easy.

You just have to append your XML string to your request body like you do, but additionaly encapsulate it between boundaries and add a content header.

NSURL *remoteURL = [NSURL URLWithString:@"http://someurl"];
NSMutableURLRequest *imageRequest = [[NSMutableURLRequest alloc] initWithURL:remoteURL];
//A unique string that will be repeated as a separator
NSString *boundary = @"14737809831466499882746641449";

//this is important so the webserver knows that you're sending multipart/form-data
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[imageRequest addValue:contentType forHTTPHeaderField: @"Content-Type"];

NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; //boundary
[body appendData:[@"Content-Disposition: form-data; name=\"xmlString\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; //your content header
[body appendData:[xmlString dataUsingEncoding:NSUTF8StringEncoding]]; //your content itself
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

[imageRequest setHTTPMethod:@"POST"]; //set Method as POST
[imageRequest setHTTPBody:body];

NSData *data = [NSURLConnection sendSynchronousRequest:imageRequest returningResponse:nil error:nil];

Or... If you want send a GET variable as part of your query string, just URL encode it and add it as part of your URL.

NSString *xmlString = @"<xml>...</xml>";
NSString *escapedString = [xmlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *urlString = [NSString stringWithFormat:@"http://someserver/?xmlString=%@",escapedString];
NSURL *url = [NSURL URLWithString:urlString];
NSLog(@"Current URL: %@", url);

This is what a request URL with a HTTP GET parameter looks like.

I hope this helps.

Upvotes: 1

Related Questions