2015-02-07 208 views
2

是否有使用AFNetworking〜> 2.0發送帶有JSON主體的POST請求?帶JSON體的POST請求AFNetworking 2.0

我已經嘗試使用:
manager.requestSerializer = [AFJSONRequestSerializer serializer]; manager POST:<url> parameters: @{@"data":@"value"} success: <block> failure: <block>'

,但它不工作。任何幫助是極大的讚賞。 謝謝

回答

5

您可以添加您的JSON正文NSMutableURLRequest不直接在parameters:。看到我的示例代碼:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 
// Set post method 
[request setHTTPMethod:@"POST"]; 
// Set header to accept JSON request 
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 
// Your params 
NSDictionary *params = @{@"data":@"value"}; 
// Change your 'params' dictionary to JSON string to set it into HTTP 
// body. Dictionary type will be not understanding by request. 
NSString *jsonString = [self getJSONStringWithDictionary:params]; 

// And finally, add it to HTTP body and job done. 
[request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]]; 

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 
manager.requestSerializer = [AFJSONRequestSerializer serializer]; 
AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request success:<block> failure:<block>]; 

希望這會幫助你。快樂的編碼! :)

1

如果有人找AFNetworking 3.0,這裏是代碼

NSError *writeError = nil; 

NSData* jsonData = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:&writeError]; 
NSString* jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding]; 

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:120]; 

[request setHTTPMethod:@"POST"]; 
[request setValue: @"application/json; encoding=utf-8" forHTTPHeaderField:@"Content-Type"]; 
[request setValue: @"application/json" forHTTPHeaderField:@"Accept"]; 
[request setHTTPBody: [jsonString dataUsingEncoding:NSUTF8StringEncoding]]; 

AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; 

[[manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { 

    if (!error) { 
     NSLog(@"Reply JSON: %@", responseObject); 

     if ([responseObject isKindOfClass:[NSDictionary class]]) { 
      //blah blah 
     } 
    } else { 

     NSLog(@"Error: %@", error); 
     NSLog(@"Response: %@",response); 
     NSLog(@"Response Object: %@",responseObject); 

    } 
}] resume];