小编典典

想要的:使用AFNetworking-2使用基本身份验证的JSON / POST的最新示例

json

我有一个玩具应用程序,它使用基本身份验证安全性提交了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或其他原因,但是我可以将应用翻转回原始代码,并且一切顺利。


阅读 272

收藏
2020-07-27

共1个答案

小编典典

更新:发现以下JSON部分可用于PUT / POST,但不适用于GET / HEAD / DELETE

经过一番争执,在SO的帮助下,我得到了一些工作,我想把它留作纪念。最后,AFNetworking-2给我留下了非常深刻的印象。它是如此简单,我一直努力使它变得比原来更难。给定一个jsonDict返回要发送的json数据包的方法,我创建了以下代码:

- (void) submitAuthenticatedRest_PUT
{
    // it all starts with a manager
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    // in my case, I'm in prototype mode, I own the network being used currently,
    // so I can use a self generated cert key, and the following line allows me to use that
    manager.securityPolicy.allowInvalidCertificates = YES;
    // Make sure we a JSON serialization policy, not sure what the default is
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    // No matter the serializer, they all inherit a battery of header setting APIs
    // Here we do Basic Auth, never do this outside of HTTPS
    [manager.requestSerializer
        setAuthorizationHeaderFieldWithUsername:@"basic_auth_username"
        password:@"basic_auth_password"];
    // Now we can just PUT it to our target URL (note the https).
    // This will return immediately, when the transaction has finished,
    // one of either the success or failure blocks will fire
    [manager
        PUT: @"https://101.202.303.404:5555/rest/path"
        parameters: [self jsonDict]
        success:^(AFHTTPRequestOperation *operation, id responseObject){
            NSLog(@"Submit response data: %@", responseObject);} // success callback block
        failure:^(AFHTTPRequestOperation *operation, NSError *error){
            NSLog(@"Error: %@", error);} // failure callback block
    ];
}

3条设置语句,然后发送2条消息,这真的很容易。

编辑/添加:这是一个@jsonDict实现示例:

- (NSMutableDictionary*) jsonDict
{
    NSMutableDictionary *result = [[NSMutableDictionary alloc] init];
    result[@"serial_id"] = self.serialID;
    result[@"latitude"] = [NSNumber numberWithDouble: self.location.latitude];
    result[@"longitude"] = [NSNumber numberWithDouble: self.location.longitude];
    result[@"name"] = self.name;
    if ([self hasPhoto])
    {
        result[@"photo-jpeg"] = [UIImageJPEGRepresentation(self.photo, 0.5)
            base64EncodedStringWithOptions: NSDataBase64Encoding76CharacterLineLength];
}
return result;

}

它应该只返回带有字符串键和简单对象作为值(NSNumber,NSString,NSArray(我认为)等)的字典。JSON编码器将为您完成其余工作。

2020-07-27