最好和最简单的方法是继承 AFHTTPClient。
使用此代码段
MBHTTPClient
#define YOUR_BASE_PATH @"http://sample.com"
#define YOUR_URL @"post.json"
#define ERROR_DOMAIN @"com.sample.url.error"
/**************************************************************************************************/
#pragma mark - Life and Birth
+ (id)sharedHTTPClient
{
static dispatch_once_t pred = 0;
__strong static id __httpClient = nil;
dispatch_once(&pred, ^{
__httpClient = [[self alloc] initWithBaseURL:[NSURL URLWithString:YOUR_BASE_PATH]];
[__httpClient setParameterEncoding:AFJSONParameterEncoding];
[__httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
//[__httpClient setAuthorizationHeaderWithUsername:@"" password:@""];
});
return __httpClient;
}
/**************************************************************************************************/
#pragma mark - Custom requests
- (void) post<#Objects#>:(NSArray*)objects
success:(void (^)(AFHTTPRequestOperation *request, NSArray *objects))success
failure:(void (^)(AFHTTPRequestOperation *request, NSError *error))failure
{
[self postPath:YOUR_URL
parameters:objects
success:^(AFHTTPRequestOperation *request, id JSON){
NSLog(@"getPath request: %@", request.request.URL);
if(JSON && [JSON isKindOfClass:[NSArray class]])
{
if(success) {
success(request,objects);
}
}
else {
NSError *error = [NSError errorWithDomain:ERROR_DOMAIN code:1 userInfo:nil];
if(failure) {
failure(request,error);
}
}
}
failure:failure];
}
然后在你的代码中调用
[[MBHTTPClient sharedHTTPClient] post<#Objects#>:objects
success:^(AFHTTPRequestOperation *request, NSArray *objects) {
NSLog("OK");
}
failure:(AFHTTPRequestOperation *request, NSError *error){
NSLog("NOK %@",error);
}
objects 是一个 NSArray(您可以将其更改为 NSDictonary)并将以 JSON 格式编码