Asynchronous HTTP POST requests in Objective-C (Cocoa Framework)

The snippets below contain a header file and an Objective-C class to send HTTP POST requests.

Header file

//
//  AsyncPost.h
//
//  Created by Ferhat Yildiz on 7/9/11.
//

#import <Foundation/Foundation.h>

@interface AsyncPost : NSObject {
	NSMutableData* httpResponse;
}

@end

Class

//
//  AsyncPost.m
//
//  Created by Ferhat Yildiz on 7/9/11.
//

#import "AsyncPost.h"

@implementation AsyncPost

- (id)init {
	self = [super init]; 

	if(self){
		httpResponse = [[NSMutableArray alloc] init];
	}

	return self;
}

// Sends an asynchronous HTTP POST request
- (void)sendRequest:(NSString*)url: (NSString*)body: (NSObject*) sender {

	NSMutableString* requestURL = [[NSMutableString alloc] init];
	[requestURL appendString:url];

	NSMutableString* requestBody = [[NSMutableString alloc] init];
	[requestBody appendString:@"request="];
	[requestBody appendString:body]; 

	NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: [NSString stringWithString:requestURL]]];

	NSString* requestBodyString = [NSString stringWithString:requestBody];
	NSData *requestData = [NSData dataWithBytes: [requestBodyString UTF8String] length: [requestBodyString length]];

	[request setHTTPMethod: @"POST"];
	[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
	[request setHTTPBody: requestData];

	[[NSURLConnection alloc] initWithRequest:request delegate:sender];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [httpResponse setLength:0];
}

// Called when data has been received
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [httpResponse appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	NSString* responseString = [[[NSString alloc] initWithData:httpResponse encoding:NSUTF8StringEncoding] copy];

	// Do something with the response

    [connection release];
    [httpResponse release];
}

@end

 

This entry was posted in Objective-C and tagged , , , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

One Comment

  1. hande canatar
    Posted May 10, 2012 at 8:23 pm | Permalink

    AsyncPost, HTTP POST request in çalışan bir örneği var mı?

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Why ask?