Skip to content

Instantly share code, notes, and snippets.

@krhoyt
Last active December 27, 2015 16:59
Show Gist options
  • Select an option

  • Save krhoyt/7359175 to your computer and use it in GitHub Desktop.

Select an option

Save krhoyt/7359175 to your computer and use it in GitHub Desktop.
Make an HTTP POST and read the response content into a string for further processing.
- ( NSString * ) loadFileHTTPFormPost : ( NSString * ) url withFormData : ( NSDictionary * ) parameters
{
NSData * post;
NSError * error;
NSHTTPURLResponse * response;
NSMutableString * location;
NSMutableURLRequest * request;
NSString * contents;
NSString * form;
// Form data
form = [self encodeDictionary : parameters];
NSLog( @"%@", form );
location = [[NSMutableString alloc] init];
// Send form data
request = [[NSMutableURLRequest alloc] init];
[request setURL : [NSURL URLWithString : url]];
[request setHTTPMethod : @"POST"];
[request setValue : [NSString stringWithFormat : @"%lu", [form length]] forHTTPHeaderField : @"Content-Length"];
[request setValue : @"application/x-www-form-urlencoded" forHTTPHeaderField : @"Content-Type"];
[request setHTTPBody : [form dataUsingEncoding : NSUTF8StringEncoding]];
error = [[NSError alloc] init];
response = nil;
post = [NSURLConnection sendSynchronousRequest : request returningResponse : &response error : &error];
if( [response statusCode] != 200 )
{
NSLog( @"Error making HTTP request: %@", error );
} else {
contents = [[NSString alloc] initWithData : post encoding:NSUTF8StringEncoding];
NSLog( @"Form data response: %@", contents );
}
return contents;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment