Skip to content

Instantly share code, notes, and snippets.

@roalcantara
Created April 20, 2012 04:23
Show Gist options
  • Save roalcantara/2425993 to your computer and use it in GitHub Desktop.
Save roalcantara/2425993 to your computer and use it in GitHub Desktop.
Easy POST with params and httpheader
//inspiration: http://stackoverflow.com/questions/5269236/http-post-of-uiimage-and-parameters-to-webserver
@implementation HTTPUtils
+(NSData*)post:(NSString*)_urlAddress
params: (NSDictionary*) _params
headers: (NSDictionary*) _headers
images: (NSDictionary*) _images {
// create the connection
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: _urlAddress]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
// change type to POST (default is GET)
[request setHTTPMethod:@"POST"];
// just some random text that will never occur in the body
NSString *stringBoundary = @"0xKhTmLbOuNdArY---This_Is_ThE_BoUnDaRyy---pqo";
// header value
NSString *headerBoundary = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",
stringBoundary];
// set header
[request addValue:headerBoundary forHTTPHeaderField:@"Content-Type"];
if(_headers != nil) {
for (NSString* key in _headers) {
[request setValue: [_headers objectForKey:key] forHTTPHeaderField:key];
}
}
//add body
NSMutableData *postBody = [NSMutableData data];
if(_params != nil) {
for (NSString* key in _params) {
id value = [_params objectForKey:key];
postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[value dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
}
}
if(_images != nil) {
for (NSString* key in _images) {
id image = [_images objectForKey:key];
//todo: get filename
NSString* filename = @"image.jpg";
//image
[postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", key, filename] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"Content-Type: image/jpeg\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"Content-Transfer-Encoding: binary\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// get the image data from main bundle directly into NSData object
NSData *imgData = UIImageJPEGRepresentation(image, 1.0);
// add it to body
[postBody appendData:imgData];
[postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
NSLog(@"message added");
}
}
// final boundary
[postBody appendData:[[NSString stringWithFormat:@"--%@--\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
// add body to post
[request setHTTPBody:postBody];
// pointers to some necessary objects
NSHTTPURLResponse* response = [[NSHTTPURLResponse alloc] init];
NSError* error = Nil;
// synchronous filling of data from HTTP POST response
NSData *responseData = [NSURLConnection sendSynchronousRequest: request
returningResponse: &response
error: &error];
NSLog(@"[HTTPUtils] just sent request to url: '%@' result: '%@' errors: '%@'", _urlAddress, responseData, error);
if (error) {
[NSException raise:@"Error" format:@"%@", [error localizedDescription]];
}
return responseData;
}
+(NSDictionary*)postToJSON:(NSString*)_urlAddress
params: (NSDictionary*) _params
headers: (NSDictionary*) _headers {
NSData* responseData = [self post:_urlAddress
params: _params
headers: _headers];
NSError* error = nil;
id result = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions error:&error];
if (error != nil) return nil;
NSLog(@"done: %@", result);
return result;
}
@roalcantara
Copy link
Author

 //Example:

 NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
 [_params setValue:@"value1" forKey:@"param1"];
 [_params setValue:@"value2" forKey:@"param2"];

 NSMutableDictionary* _headers = [[NSMutableDictionary alloc] init];
 [_params setValue:@"auth_token" forKey:@"token"];

 NSMutableDictionary* _uiimages = [[NSMutableDictionary alloc] init];
 [_params setValue:_uiimage forKey:@"photo1.jpg"];

NSData* result = [HTTPUtils post:@"http://your.site/and/action/"
                                         params: _params
                                        headers: _headers
                                        images: _uiimages];

@roalcantara
Copy link
Author

//Example using url JSON:

NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
[_params setValue:@"value1" forKey:@"param1"];
[_params setValue:@"value2" forKey:@"param2"];

NSMutableDictionary* _headers = [[NSMutableDictionary alloc] init];
[_params setValue:@"auth_token" forKey:@"token"];

NSMutableDictionary* _uiimages = [[NSMutableDictionary alloc] init];
[_params setValue:_uiimage forKey:@"photo1.jpg"];

NSDictionary* resultOfJson = [HTTPUtils postToJSON:@"http://your.site/and/action/json/"
params: _params
headers: _headers
images: _uiimages];

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment