我有一个玩具应用程序,它使用基本身份验证安全性提交 https JSON/POST。有人告诉我应该考虑使用 AFNetworking。我已经能够将 AFNetwork-2 安装到我的 XCode 项目(ios7 目标,XCode5)中就好了。但是那里的示例似乎都与当前版本的 AFNetworking-2 无关,而是与以前的版本相关。AFNetworking 文档非常稀少,所以我正在努力如何将这些部分组合在一起。非 AFNetworking 代码如下所示:
NSURL *url = [NSURL URLWithString:@"https://xxx.yyy.zzz.aaa:bbbbb/twig_monikers"];
NSMutableURLRequest *request = [NSMutableURLRequest
requestWithURL:url
cachePolicy: NSURLRequestUseProtocolCachePolicy
timeoutInterval: 10.0];
NSData *requestData = [NSJSONSerialization dataWithJSONObject: [self jsonDict] options: 0 error: nil];
[request setHTTPMethod: @"POST"];
[request setValue: @"application/json" forHTTPHeaderField: @"Accept"];
[request setValue: @"application/json" forHTTPHeaderField: @"Content-Type"];
[request setValue:[NSString stringWithFormat: @"%d", [requestData length]] forHTTPHeaderField: @"Content-Length"];
NSData *plainPassText = [@"app_pseudouser:sample_password" dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64PassText = [plainPassText base64EncodedStringWithOptions: NSDataBase64Encoding76CharacterLineLength];
[request setValue:[NSString stringWithFormat: @"Basic %@", base64PassText] forHTTPHeaderField: @"Authorization"];
FailedCertificateDelegate *fcd=[[FailedCertificateDelegate alloc] init];
NSURLConnection *c=[[NSURLConnection alloc] initWithRequest:request delegate:fcd startImmediately:NO];
[c setDelegateQueue:[[NSOperationQueue alloc] init]];
[c start];
NSData *data=[fcd getData];
if (data)
NSLog(@"Submit response data: %@", [NSString stringWithUTF8String:[data bytes]]);
我不是在找人为我编写代码。我似乎无法弄清楚如何将 AFNetworking-2 部分映射到该部分。非常欢迎任何链接、示例或解释。
更新 1
以上是已知可以工作的非 AF 版本。试图一口气完成所有工作,我只是尝试过:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer
setAuthorizationHeaderFieldWithUsername:@"app_pseudouser"
password:@"sample_password"];
AFHTTPRequestOperation *operation =
[manager
PUT: @"https://172.16.214.214:44321/twig_monikers"
parameters: [self jsonDict]
success:^(AFHTTPRequestOperation *operation, id responseObject){
NSLog(@"Submit response data: %@", responseObject);}
failure:^(AFHTTPRequestOperation *operation, NSError *error){
NSLog(@"Error: %@", error);}
];
这会产生以下错误:
2013-10-09 11:41:38.558 TwigTag[1403:60b] Error: Error Domain=NSURLErrorDomain Code=-1012 "The operation couldn’t be completed. (NSURLErrorDomain error -1012.)" UserInfo=0x1662c1e0 {NSErrorFailingURLKey=https://172.16.214.214:44321/twig_monikers, NSErrorFailingURLStringKey=https://172.16.214.214:44321/twig_monikers}
在服务器端观看,没有任何东西可以通过。我不知道是因为https还是什么,但是我可以将应用程序翻转回原始代码,并且可以正常运行。