AFHTTPClient*httpClient=[[AFHTTPClientalloc]initWithBaseURL:[NSURLURLWithString:@"http://samwize.com/"]];NSMutableURLRequest*request=[httpClientrequestWithMethod:@"GET"path:@"http://samwize.com/api/pigs/"parameters:nil];AFHTTPRequestOperation*operation=[[AFHTTPRequestOperationalloc]initWithRequest:request];[httpClientregisterHTTPOperationClass:[AFHTTPRequestOperationclass]];[operationsetCompletionBlockWithSuccess:^(AFHTTPRequestOperation*operation,idresponseObject){// Print the response body in textNSLog(@"Response: %@",[[NSStringalloc]initWithData:responseObjectencoding:NSUTF8StringEncoding]);}failure:^(AFHTTPRequestOperation*operation,NSError*error){NSLog(@"Error: %@",error);}];[operationstart];
POST
POST a urlencoded form name=piggy in the http body.
1234567
AFHTTPClient*httpClient=[[AFHTTPClientalloc]initWithBaseURL:[NSURLURLWithString:@"http://samwize.com/"]];[httpClientsetParameterEncoding:AFFormURLParameterEncoding];NSMutableURLRequest*request=[httpClientrequestWithMethod:@"POST"path:@"http://samwize.com/api/pig/"parameters:@{@"name":@"piggy"}];// Similar to GET code ...
If you want to POST a json such as {"name":"piggy"}, you change the encoding:
This simple guide has been helped by this, this and this.
Pitfalls
Do not use [[AFHTTPClient alloc] init], as that does not initialize a lot of stuff. Use initWithBaseURL instead.
For instance, if in the above example (POST JSON) you had used init, the Content-Type will be
application/json; charset=(null)
Charset should be utf-8, not null
Thank you very much Joseph it worked very well. I just had a question after I alloc the httpClient I release it after creating the request, I dont seem to have any crashes and seems to work well. I just wanted to confirm that that is the correct spot to release it. Thank you very much again. Kind Regards – Sam BarnetOct 2 '11 at 20:13
1
Yes, that would works. The AFHTTPClient is really intended to be kept around and used again if you make another request, but releasing it straight after the 'requestWithMethod:' call is acceptable. – JosephHOct 2 '11 at 21:22
hey sorry to make this out of the blue but I have been looking everywhere on what to import however, it just doesnt do it for me I have imported #import "AFHTTPRequestOperation.h" #import "AFHTTPClient.h" #import "ASIHTTPRequest.h" #import "ASIFormDataRequest.h" #import <Foundation/Foundation.h> yet it still doesnt work :( – chaitanya.varanasiJul 12 at 14:51