POST with NSURLConnection - NO JSON
Solution 1
Here's how to create an ordinary post.
First create a request of the right type:
NSURL *URL = [NSURL URLWithString:@"http://example.com/somepath"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
request.HTTPMethod = @"POST";
Now format your post data as a URL-encoded string, like this:
NSString *params = @"param1=value1¶m2=value2&etc...";
Remember to encode the individual parameters using percent encoding. You can't entirely rely on the NSString stringByAddingPercentEscapesUsingEncoding method for this (google to find out why) but it's a good start.
Now we add the post data to your request:
NSData *data = [params dataUsingEncoding:NSUTF8StringEncoding];
[request addValue:@"8bit" forHTTPHeaderField:@"Content-Transfer-Encoding"];
[request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request addValue:[NSString stringWithFormat:@"%i", [data length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:data];
And that's it, now just send your request as normal using NSURLConnection (or whatever).
To interpret the response that comes back, see Maudicus's answer.
Solution 2
You can use the following NSURLConnection method if you target ios 2.0 - 4.3 (It seems to be deprecated in ios 5)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSString * string = [[NSString alloc] initWithData:data encoding:
NSASCIIStringEncoding];
if (string.intValue == 1) {
} else {
}
}
whitebreadb
Updated on June 06, 2022Comments
-
whitebreadb almost 2 years
I am trying to write an iPhone app in Objective-C. I need to POST data using NSURLConnection. Every example I can find deals with JSON; I do not need to use JSON. All I need to do is POST the data and get a simple 1 or 0 (succeed or fail) from a PHP script. Nothing more.
I came across this code but I am not sure how to use it or modify it to not use JSON:
- (void)performRequest { NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://someplace.com/"]]; [request setValue:@"Some Value" forHTTPHeaderField:@"Some-Header"]; [request setHTTPBody:@"{\"add_json\":\"here\"}"]; [request setHTTPMethod:@"POST"]; [NSURLConnection connectionWithRequest:[request autorelease] delegate:self]; } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { // Fail.. } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { // Request performed. }