Reputation: 51
I'm building an iPhone client that will GET and POST to a REST service. The GET-part works fine, but I don't seem to be able to POST anything. The server only accepts xml at the moment. I've tried to use ASIHTTPRequest, ASIFormDataRequest and doing it myself but nothing seems to work. Can anyone help me? I'm fairly new to Objective-C programming.
I do get a status code: 200 as a response using the following code in didReceiveResponse:
NSHTTPURLResponse * httpResponse;
httpResponse = (NSHTTPURLResponse *) response;
int myStatus = httpResponse.statusCode;
if (myStatus == 400) {
NSLog(@"Status code: 400");
} else if (myStatus == 200) {
NSLog(@"Status code: 200");
} else {
NSLog(@"Other status code");
Here follows three different approaches...
Code (ASIHTTPRequest):
NSURL *url = [NSURL URLWithString:@"myUrl.com"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request appendPostData:[@"<my xml>" dataUsingEncoding:NSUTF8StringEncoding]];
// Default becomes POST when you use appendPostData: / appendPostDataFromFile: / setPostBody:
[request setRequestMethod:@"POST"];
[request setDelegate:self];
[request startSynchronous];
Code (ASIFormDataRequest):
NSURL *url = [NSURL URLWithString:@"someUrl.com"];
ASIFormDataRequest *theRequest = [ASIFormDataRequest requestWithURL:url];
// [theRequest setPostValue:@"" forKey:@"key1"];
[theRequest setPostValue:@"90" forKey:@"key2"];
[theRequest setPostValue:@"150" forKey:@"key3"];
// [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:TRUE];
[theRequest startAsynchronous];
Code (Third method):
NSData *myPostData = [[NSString stringWithFormat:@"<my xml>"] dataUsingEncoding:NSUTF8StringEncoding];//NSASCIIStringEncoding];
// NSString *xmlPostData = @"<my xml>";
NSURL *theURL = [NSURL URLWithString:@"someUrl.com"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL];
[theRequest setHTTPMethod:@"POST"];
[theRequest setValue:@"application/xml; charset=utf-8" forHTTPHeaderField:@"Content-type"];
// [theRequest setValue:@"UTF-8" forHTTPHeaderField:@"Charset"];
[theRequest setHTTPBody:myPostData];// [xmlPostData dataUsingEncoding:NSUTF8StringEncoding]];// myPostData];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:TRUE];
How about all these -(void)connection: style functions? Does any of them have to contain specific code for the connection to work?
Many thanks for any help!
Upvotes: 3
Views: 3261
Reputation: 51
NSURL *url = [NSURL URLWithString:@"http://myURL.com"];
ASIHTTPRequest *request = [ASIFormDataRequest requestWithURL:url];
NSData *myPostData = [[NSString stringWithFormat:@"<My XML Body>"] dataUsingEncoding:NSUTF8StringEncoding];//NSASCIIStringEncoding];
NSMutableData *myMutablePostData = [NSMutableData dataWithData:myPostData];
[request addRequestHeader:@"Content-Type" value:@"application/xml"];
[request setPostBody:myMutablePostData];
[request setDelegate:self];
[request startSynchronous];
Upvotes: 2